为什么 sin^2(a)+cos^2(a) 的整数类型转换返回 0 而不是 1?

Sau*_*ash 1 c trigonometry typecasting-operator

当我打印 sin(theta) * sin(theta)+ cos(theta)* cos(theta) 时,它等于 1.000000。但是当我将相同的表达式转换为 int 时,结果为 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;
 }
Run Code Online (Sandbox Code Playgroud)

Ste*_*art 5

当您将浮点数转换为整数时,它只会删除小数点后的所有数字。您的 1.0000 实际上可能更接近 0.99999999999999,这是由于仅使用有限位数来表示数字而导致的舍入误差。所有浮点数都存在此问题。因此,在处理浮点数时,永远不要期望得到确切的答案。

您的显示将结果四舍五入为 1.00000。但是,当 0.999999 转换为 int 时,它会舍去小数位,因此最终结果为 0。

您可以使用round()orroundf()函数来确保它按您的预期进行舍入。(参考)

 #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;
 }
Run Code Online (Sandbox Code Playgroud)