设置浮点数的精度

Setting precision of floating point number

本文关键字:精度 浮点数 设置      更新时间:2023-10-16

大家好,我是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对象的操作从左向右执行,"箭头"方向无关。这些方法名只是语法糖。