簡體   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