你如何在C++中四舍五入小数点
How do you round off decimal places in C++?
我需要帮助将浮点值四舍五入到小数点后一位。
我知道setprecision(x)
和cout << precision(x)
。如果我想对整个浮点值进行四舍五入,这两种方法都有效,但我只对将小数点四入到十分位感兴趣。
还有一种不需要强制转换为int的解决方案:
#include <cmath>
y = floor(x * 10d) / 10d
#include <cmath>
int main() {
float f1 = 3.14159f;
float f2 = 3.49321f;
std::cout << std::floor(f1 * 10 + 0.5) / 10 << std::endl;
std::cout << std::floor(f2 * 10 + 0.5) / 10 << std::endl;
std::cout << std::round(f1 * 10) / 10 << std::endl; // C++11
std::cout << std::round(f2 * 10) / 10 << std::endl; // C++11
}
您可以这样做:
int main()
{
float a = 4212.12345f;
float b = a * 10.0f;
float c = ((int)b) / 10.0f;
cout << c << endl;
return 0;
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 用c++把小数点转换成八进制
- 在除法中不需要四舍五入
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 使用 cin 时接受小数点后的 2 位数字
- 四舍五入C++
- 如何在C或C 的小数点后两个位置后四舍五入
- 如何在c++中将一个变量四舍五入到小数点后的n位
- 你如何在C++中四舍五入小数点
- 四舍五入双小数点后两位
- 变体浮点数到双精度值转换,四舍五入到小数点后 1 位
- C++四舍五入小数点后两位
- 如何将双精度四舍五入到小数点后n位c++
- 将浮点数四舍五入到小数点后一位,然后转换为字符串
- 四舍五入浮点数:精确地输出小数点后的两位数字
- 我需要知道如何在c++中将数字四舍五入到小数点后的某个位置
- 将双精度值四舍五入到小数点后3位
- 将双数四舍五入到小数点后3点