任何人都可以告诉我为什么第9行和第11行的计算看似相同,产生两种不同的输出.我知道差异并不是那么大,但我使用这些值来绘制OpenGL线条,差别很明显.
#include <iostream>
#include <cmath>
int main()
{
int ypos=400;
/// Output: 410.
std::cout << 400+(sin((90*3.14159)/180)*10) << std::endl;
ypos=ypos+(sin((90*3.14159)/180)*10);
/// Output: 409.
std::cout << ypos << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输出浮点数
std::cout << 400+(sin((90*3.14159)/180)*10) << std::endl;
Run Code Online (Sandbox Code Playgroud)
但这是输出一个整数,因此会被截断
std::cout << ypos << std::endl;
Run Code Online (Sandbox Code Playgroud)
在真正的答案是围绕某个地方409.9999999.
这是输出a double和舍入到410因为数学全部内联:
std::cout << 400+(sin((90*3.14159)/180)*10) << std::endl;
Run Code Online (Sandbox Code Playgroud)
因为ypos声明为a int,所以double值被截断为409(从doubleto 转换为定义的行为int):
ypos=ypos+(sin((90*3.14159)/180)*10);
/// Output: 409.
std::cout << ypos << std::endl;
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以通过为PI使用更好的常量来提高准确性:
const double PI = 3.141592653589793238463;
std::cout << 400+(sin((90*PI)/180)*10) << std::endl;
Run Code Online (Sandbox Code Playgroud)
但我仍然会将结果存储在一个double而不是一个int以避免截断.如果你需要一个整数结果,我会先圆:
ypos += round(sin((90*PI)/180)*10);
Run Code Online (Sandbox Code Playgroud)