简体   繁体   English

浮点数设置精度

[英]Setting precision of floating point number

Hello guys I am new in C++ I am trying to write the function to calculate the second moment of inertia and set the precision with 3 decimal places. 大家好,我是C ++的新手,我正在尝试编写该函数来计算第二个惯性矩并将精度设置为3个小数位。 In the output does not apply the 3 decimal places in the first call but the following 4 calls does applied. 在输出中,第一个调用不应用小数点后3位,但随后的四个调用被应用。 Here is my codes , please help me find the error and if possible please explain some details thank you very much ! 这是我的代码,请帮助我找到错误,如果可能,请解释一些细节,非常感谢!

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;
}

The output in my text file is as follow : 我的文本文件中的输出如下:

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 

You have to set stream precision before printing a number. 您必须打印数字之前设置流精度。

ofs << 5.5555 << setprecision(3) << endl; // prints "5.5555"
ofs << setprecision(3) << 5.5555 << endl; // prints "5.555"

Stream operators << and >> are, in fact, methods that can be chained. 实际上,流运算符<<>>是可以链接的方法。 Let's say we have a piece of example java code like: 假设我们有一段示例Java代码,例如:

dog.walk().stopByTheTree().pee();

In C++, if we'd use stream operators, it'd look like: 在C ++中,如果我们使用流运算符,则它看起来像:

dog << walk << stopByTheTree << pee;

Operations on dog objects are executed from left to right, and the direction of "arrows" doesn't matter. dog对象的操作从左到右执行,“箭头”的方向无关紧要。 These method names are just syntactic sugar. 这些方法名称只是语法糖。

Look here for more details. 在这里查看更多详细信息。

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

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