Search code examples
ctrigonometrytypecasting-operator

Why does the Integer Type Conversion of sin^2(a)+cos^2(a) return 0 instead of 1?


When I'm printing sin(theta) * sin(theta)+ cos(theta)* cos(theta), it's coming out to be equal to 1.000000. But when I'm typecasting the same expression into int, the result comes out to be 0.

 #include< stdio.h >
 #include< math.h >
 #define PI acos(-1)
 int main()
 {
     float theta;
     printf("Theta : ");
     scanf("%f",&theta);
     theta=theta*PI/180;
     printf("%f\n",sin(theta)*sin(theta)+cos(theta)*cos(theta));
     printf("%d\n",(int)(sin(theta)*sin(theta)+cos(theta)*cos(theta)));
     return 0;
 }

Solution

  • When you cast a floating-point number to an integer, it just drops all digits after the decimal-point. Your 1.0000 is probably actually something closer to 0.99999999999999 due rounding errors caused by the fact that only a finite number of bits are used to represent a number. All floating-point numbers are subject to this issue. Therefore never expect an EXACT answer when dealing with floating-point numbers.

    Your display is rounding the result to 1.00000. However, when 0.999999 is casted to an int, it drops the decimals and so it ends up with 0.

    You can use the round() or roundf() function to ensure it is rounded as you expected. (reference)

     #include< stdio.h >
     #include< math.h >
     #define PI acos(-1)
    
     int main()
     {
         float theta;
         printf("Theta : ");
         scanf("%f",&theta);
         theta=theta*PI/180;
    
         float resultf  = sin(theta)*sin(theta)+cos(theta)*cos(theta);
         int   resulti  = roundf(resultf);
         printf("%f\n",resultf);
         printf("%d\n",resulti);
         return 0;
     }