c++ 为什么使用int将这个计算四舍五入到小数点后一位不起作用?

1l5u6lss  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(155)
#iclude <iostream>
#include <cmath>
#include <math.h>
using namespace std;

int main()
{
    double speed = 5;
    int temp = -5;
    int windChill;
    double roundedWindChill;

    windChill = ((35.74 + (0.6215 * temp) - (35.75 * pow(speed, 0.16)) + (0.4275 * temp *   (pow(speed0.16)))) * 10.0) + 0.5;
    roundedWindChill = windChill / 10.0;
        cout << roundedWindChill;
}

当我运行这个程序时,我得到了16.3,但是我应该得到16.4,因为加上一个数字的答案是16.37。不知道为什么这不是四舍五入。
谢谢你的帮助!

d4so4syb

d4so4syb1#

由于C++中的整数除法规则,结果会朝零截断。
假设我们有下面的代码:

int a = 8;
int b = 3;
int c = a / b;

该值将为2。
在您的代码中,表达式windChill / 10.0正在执行这样的除法,它将丢弃任何小数位,并将结果向下舍入到最接近的整数。
要解决此问题,请使用<cmath>库中的std::round()除以10.0之前对 windChill进行四舍五入。

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double speed = 5;
    int temp = -5;
    int windChill;
    double roundedWindChill;

    windChill = round((35.74 + (0.6215 * temp) - (35.75 * pow(speed, 0.16)) + (0.4275 * temp * (pow(speed,0.16)))) * 10.0);
    roundedWindChill = windChill / 10.0;
    cout << roundedWindChill;
}

相关问题