gpt4 book ai didi

c++ - 不需要的舍入四舍五入

转载 作者:行者123 更新时间:2023-12-02 10:35:56 28 4
gpt4 key购买 nike

我有一个20位长的数组;我想找到数组中所有负数的算术平均值,然后从该数组的每个元素中减去该数。
问题是,当我尝试将负数的值的总和除以负数的数量(以求平均值)时,它会自动四舍五入为最接近的整数

这是代码:

int main()
{
double a1 = 0.0;
double b2 = 0.0; // arth mean
int arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
for(int i = 0; i < 20; i++) {
if(arr[i] < 0) {
a1 += arr[i]; // sum of negative numbers
}
}
b2 = a1 / 6;
cout << b2;
for(int i = 0; i < 20; i++) {
arr[i] = arr[i] - b2;
}
for(int i = 0; i < 20; i++) {
cout << arr[i] << " ";
}

return 0;
}

最佳答案

您正在对arr进行更改,它是int类型的数组,因此每种 float 数据类型都会自动更改为忽略小数点,而剩余的数字为int,即int 5 = 5.9;等于5,这是最后一行的答案。因此,将数组arr转换为float或double数据类型。

 float arr[20] = {12, -30, 23, -43, 51, 26, 0, 88, 19, -10, 11, 2, 23, -14, 15, 6, -7, 1, -19, 120};
for(int i = 0; i < 20; i++) {
if(arr[i] < 0) {
a1 += arr[i]; // sum of negative numbers
}
}

关于c++ - 不需要的舍入四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com