繁体   English   中英

浮点数设置精度

[英]Setting precision of floating point number

大家好,我是C ++的新手,我正在尝试编写该函数来计算第二个惯性矩并将精度设置为3个小数位。 在输出中,第一个调用不应用小数点后3位,但随后的四个调用被应用。 这是我的代码,请帮助我找到错误,如果可能,请解释一些细节,非常感谢!

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对象的操作从左到右执行,“箭头”的方向无关紧要。 这些方法名称只是语法糖。

在这里查看更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM