Getting different output from seemingly identical calculations

前端 未结 4 334
抹茶落季
抹茶落季 2021-01-21 03:15

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 the

4条回答
  •  失恋的感觉
    2021-01-21 03:50

    The real answer is somewhere around 409.9999999.

    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;
    

    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;
    

    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;
    

    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);
    

提交回复
热议问题