[英]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. 当我打印sin(θ)* sin(θ)+ cos(θ)* cos(theta)时,等于1.000000。 But when I'm typecasting the same expression into int, the result comes out to be 0.
但是,当我将相同的表达式类型转换为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;
}
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.
您的1.0000实际上可能更接近0.99999999999999,原因是由于仅使用有限数量的位来表示数字而导致的舍入误差。 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. 您的显示将结果舍入为1.00000。 However, when 0.999999 is casted to an int, it drops the decimals and so it ends up with 0.
但是,将0.999999转换为int时,它将删除小数,因此最终以0结尾。
You can use the round()
or roundf()
function to ensure it is rounded as you expected. 您可以使用
round()
或roundf()
函数来确保将其四舍五入。 (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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.