C ++将双精度取整至小数点后2位 [英] C++ round a double up to 2 decimal places
问题描述
我无法将GPA的整数四舍五入到小数点后两位.(例如,需要对GPA进行四舍五入:3.67924)我目前正在使用ceil进行四舍五入,但是目前将其输出为整数(368)
I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368)
这是我现在拥有的
if (cin >> gpa) {
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
break;
} else {
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
将上面的代码与3.67924一起使用将输出368(这是我想要的,但是没有整数和小数点之间的句点).我该如何解决?
using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?
推荐答案
要舍弃小数点后2位小数,可以使用:
To round a double up to 2 decimal places, you can use:
#include <iostream>
#include <cmath>
int main() {
double value = 0.123;
value = std::ceil(value * 100.0) / 100.0;
std::cout << value << std::endl; // prints 0.13
return 0;
}
要舍入到小数点后n位,您可以使用:
To round up to n decimal places, you can use:
double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
这种方法并不是特别快,如果性能成为问题,您可能需要其他解决方案.
This method won't be particularly fast, if performance becomes an issue you may need another solution.
这篇关于C ++将双精度取整至小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!