Home>

I am a C language beginner.
I am creating a program that inputs resistors r1 and r2 and outputs series and parallel combined resistors to c and h, respectively, but printf is not output after input,
Integer division by zero.
It comes out.

(If the resistance value is negative, I would like to input it again.)
If there are any mistakes, please let me know.

# include<stdio.h>
# include<stdlib.h>
# include<math.h>
int main (void)
{
              int r1, r2, c, h;
              printf ("r1 =");
              scanf ("% d",&r1);
              printf ("r2 =");
              scanf ("% d",&r2);
              if (r1<0 || r2<0)
              {
                            printf ("r1 =");
                            scanf ("% d",&r1);
                            printf ("r2 =");
                            scanf ("% d",&r2);
              }
              else
              {
                            c = r1 + r2;
                            h = 1/((1/r1) + (1/r2));
              }
              printf ("% d,% d", c, h);
    system ("PAUSE");
    return 0;
}
c
  • Answer # 1

    R1 and r2 are integer types, so r1 or r2 must be 1
    The calculation result becomes 0 during the process, and a divide by zero error occurs.

    h = 1/((1/r1) + (1/r2));

    Usually, use float or double, which can calculate decimal places.

  • Answer # 2

    I was able to resolve myself. excuse me.
    This is not the comment field.
    I'll be careful.