舍入应该返回的双精度变量,而不是打印
Rounding a double variable that is supposed to be returned, as opposed to printed
我正在编写一个平均函数,它取数组的平均值,returns 将答案保留到小数点后 2 位。然而,我在网上找到的唯一方法是使用 printf()
或 cout()
。
但我不希望每次调用此函数时都打印出来,因为它用于其他函数,例如不应显示平均函数的方差方程和标准差方程。
如果有人能告诉我这样做的方法,我将永远感激不已。我认为我的问题足够广泛,实际上并不需要代码,但无论如何这里都是为了以防万一。它只是持续了相当多的小数点。不确定这是准确值还是分界点。
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return addsum;
}
您可以将值截断并移回原位。
示例代码
double round(double value, unsigned n)
{
double shift = std::pow(10, n);
value *= shift;
value = (int) value;
value /= shift;
return value;
}
int main()
{
double value = 1.23456;
std::cout << "before: " << value << ", after: " << round(value, 2) << "\n";
return 0;
}
注意事项:此代码可能不足以满足所有用例(例如,当将大数字 and/or 舍入到许多小数位时)
示例输出
before: 1.23456, after: 1.23
由于浮点值始终是二进制的,因此您能做的最好的事情就是 return 最接近您真正想要的十进制数的二进制数。但是这个过程相对容易。
double round_two_places(double x)
{
return floor(x * 100.0 + 0.5) / 100.0;
}
std::round
为您提供与其参数最接近的整数。要模拟小数点后第三位数字的舍入,请使用 std::round(addsum*100.0)/100.0
.
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return std::round(addsum*100.0)/100.0;
}
按以下方式使用头文件 math.h
中的 ceil
函数四舍五入到小数点后两位:
double avg(int a[], int n)
{
double addsum = (double) sum(a, n) / (double) n;
addsum = ceil(x * 100.0 - 0.5) / 100.0;
return addsum;
}
我正在编写一个平均函数,它取数组的平均值,returns 将答案保留到小数点后 2 位。然而,我在网上找到的唯一方法是使用 printf()
或 cout()
。
但我不希望每次调用此函数时都打印出来,因为它用于其他函数,例如不应显示平均函数的方差方程和标准差方程。
如果有人能告诉我这样做的方法,我将永远感激不已。我认为我的问题足够广泛,实际上并不需要代码,但无论如何这里都是为了以防万一。它只是持续了相当多的小数点。不确定这是准确值还是分界点。
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return addsum;
}
您可以将值截断并移回原位。
示例代码
double round(double value, unsigned n)
{
double shift = std::pow(10, n);
value *= shift;
value = (int) value;
value /= shift;
return value;
}
int main()
{
double value = 1.23456;
std::cout << "before: " << value << ", after: " << round(value, 2) << "\n";
return 0;
}
注意事项:此代码可能不足以满足所有用例(例如,当将大数字 and/or 舍入到许多小数位时)
示例输出
before: 1.23456, after: 1.23
由于浮点值始终是二进制的,因此您能做的最好的事情就是 return 最接近您真正想要的十进制数的二进制数。但是这个过程相对容易。
double round_two_places(double x)
{
return floor(x * 100.0 + 0.5) / 100.0;
}
std::round
为您提供与其参数最接近的整数。要模拟小数点后第三位数字的舍入,请使用 std::round(addsum*100.0)/100.0
.
double avg(int a[],int n) // compute the average of n data storing in the array a
{
double addsum = (double)sum(a,n)/(double)n;
return std::round(addsum*100.0)/100.0;
}
按以下方式使用头文件 math.h
中的 ceil
函数四舍五入到小数点后两位:
double avg(int a[], int n)
{
double addsum = (double) sum(a, n) / (double) n;
addsum = ceil(x * 100.0 - 0.5) / 100.0;
return addsum;
}