从看似相同的计算中获得不同的输出 [英] Getting different output from seemingly identical calculations

查看:64
本文介绍了从看似相同的计算中获得不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么第9行和第11行的计算似乎相同,却产生两个不同的输出.我知道差别不是很大,但是我正在使用这些值在OpenGL中绘制线条,差别非常明显.

Can anyone tell me why the calculations on lines 9 and 11, which seem to be identical, produce two different outputs. I know the difference isn't that great, but I am using these values to draw lines with OpenGL and the difference is noticeable.

#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;
}

推荐答案

real 答案在409.9999999附近.

这是输出double并四舍五入为410的原因,因为数学都是内联的:

This is outputting a double and rounding to 410 because the math is all inlined:

std::cout <<  400+(sin((90*3.14159)/180)*10) << std::endl;

由于ypos被声明为int,因此将double值截断了 409(这是从double投射到int时定义的行为):

since ypos is declared as an int, the double value is being truncated to 409 (which is the defined behavior when casting from double to int):

ypos=ypos+(sin((90*3.14159)/180)*10);

/// Output: 409.
std::cout << ypos << std::endl;

请注意,您也可以通过为PI使用更好的常数来提高准确性:

Note that you could also increase the accuracy by using a better constant for PI:

const double PI = 3.141592653589793238463;

std::cout <<  400+(sin((90*PI)/180)*10) << std::endl;

,但我仍将结果存储在double中,而不是在int中,以避免被截断.如果您需要一个整数结果,那么我将首先取整:

but I would still store the result in a double instead of an int to avoid truncating. If you need an integer result then I would round first:

ypos += round(sin((90*PI)/180)*10);

这篇关于从看似相同的计算中获得不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆