设置浮点数的精度
Setting precision of floating point number
大家好,我是c++的新手我试图写函数来计算第二个转动惯量,并设置精度与小数点后3位。在输出中不应用第一次调用中的3位小数,但应用了接下来的4次调用。这是我的代码,请帮我找出错误,如果可以请解释一些细节,非常感谢!
double beamMoment(double b, double h) //the function that calculating the second moment of inertia
{
double I; //variables b=base, h=height, I= second moment of inertia
I = b * (pow(h, 3.0) / 12); // formular of the second momeent of inertia
ofs << "b=" << b << "," << "h=" << h << "," << "I=" << I << setprecision(3) << fixed << endl;
ofs << endl;
return I;
}
int main()
{
beamMoment(10,100);
beamMoment(33, 66);
beamMoment(44, 88);
beamMoment(26, 51);
beamMoment(7, 19);
system("pause");
return 0;
}
我的文本文件的输出如下所示:
b=10,h=100,I=833333
b=33.000,h=66.000,I=790614.000
b=44.000,h=88.000,I=2498730.667
b=26.000,h=51.000,I=287410.500
b=7.000,h=19.000,I=4001.083
必须在打印数字之前设置流精度
ofs << 5.5555 << setprecision(3) << endl; // prints "5.5555"
ofs << setprecision(3) << 5.5555 << endl; // prints "5.555"
流操作符<<
和>>
实际上是可以链接的方法。假设我们有一段示例java代码,如:
dog.walk().stopByTheTree().pee();
在c++中,如果使用流操作符,它看起来像:
dog << walk << stopByTheTree << pee;
对dog
对象的操作从左向右执行,"箭头"方向无关。这些方法名只是语法糖。
相关文章:
- 使用浮点数和双精度数的非常小数字的数学
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 位设置为浮点数或双精度值 c++
- 为什么浮点数的矢量化比双精度更有效?
- 在C++中序列化浮点数/双精度,编译为 WebAssembly
- 为什么编译器接受具有长双精度文本的浮点数的初始化?
- C++ 警告:在一个声明中将截断从双精度初始化为浮点数,但在另一个声明中则不初始化
- 在 OpenCL 内核中实现半精度浮点数据类型
- 如何随机化双精度/浮点数据类型? C++
- 提升多精度浮点数128:标准::exp错误:'no matching function for call'
- 如何提高计算浮点数的精度?
- atof() 返回浮点数而不是双精度
- 如何以最大精度(C++)将uint64_t转换为0到1之间的双精度/浮点数?
- 单个精度浮点数上的第 24 个分数位在哪里?IEEE 754
- 在C++中实现半精度浮点数
- C++双精度/浮点数的内部表示
- 清除单个精度浮点数的位
- 将双精度浮点数舍入到最接近且更大的浮点数
- 如何判断双精度浮点数是否可以安全地存储为单精度浮点数
- 用于高精度浮点数的c++类型