簡體   English   中英

如何在C ++中正確設置雙精度的精度

[英]How to properly set precision for doubles in C++

我正在做一個項目,我需要做一些數學運算,並在其中提供帶美元的用戶輸出,因此我想讓控制台告訴用戶一個像$20.15而不是$20.153 我這樣使用了set precision函數: cout << setprecision(2); ,而不是讓數字變成我想要的數字,而是將其轉換為科學計數法。

我輸出了很多數字,因此對於我來說,使用setprecision類的功能對我來說是最好的。

如何正確顯示僅用小數點后兩位數字顯示的數字,而不使控制台以科學計數形式顯示數字?

謝謝

彌敦道

編輯:

這是我遇到問題的部分代碼:

int main() {

cout << setprecision(2);

if (totalCostHybrid < totalCostNonHybrid) {
            cout << "Hybrid car: " << endl;
            cout << "Total cost: " << totalCostHybrid << endl;
            cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
            cout << "Total gas cost: " << gasCostHybrid << endl;
            cout << "Non-hybrid car: " << endl;
            cout << "Total cost: " << totalCostNonHybrid << endl;
            cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
            cout << "Total gas cost: " << gasCostNonHybrid << endl;
            cout << "Hybrid is cheaper!" << endl;
}

顯然還有更多,但這是我需要幫助的。

Iostream是格式化浮點值的痛苦。 但是,為什么要使用浮點數來表示貨幣值? 您應該存儲整數美分(或十分之一美分),因為盡管您沒有用整數來衡量,但您的值實際上是定點的。 您真的不需要浮點運算帶來的麻煩。 然后,您可以分別將值的整個和“小數”部分(使用/% !)以整數形式用'.' 在中間。

同時,嘗試使用std::fixed

要解決此問題,您應該對cout使用固定的浮點符號。 您可以在此處找到更多信息。

嘗試將addind cout << fixed到您的代碼,例如下面的代碼。 要將precision設置為2 ,可以使用precision屬性。

cout << fixed;
cout.precision(2);

這是完整的代碼:

using namespace std;

int main() {

    cout << fixed;
    cout.precision(2);

    if (totalCostHybrid < totalCostNonHybrid) {
            cout << "Hybrid car: " << endl;
            cout << "Total cost: " << totalCostHybrid << endl;
            cout << "Total gallons used: " << milesPerYear / hybridEffic << endl;
            cout << "Total gas cost: " << gasCostHybrid << endl;
            cout << "Non-hybrid car: " << endl;
            cout << "Total cost: " << totalCostNonHybrid << endl;
            cout << "Total gallons used: " << milesPerYear / nonHybridEffic << endl;
            cout << "Total gas cost: " << gasCostNonHybrid << endl;
            cout << "Hybrid is cheaper!" << endl;
     }
}

作弊和看純粹主義者發瘋...

    double time;  //Only want two decimal places.
    double timeCon = time * 100.0;  //Pull out the two decimals I want.
    int timeCut = timeCon;  //Cut all decimal values.
    double timeRevert = timeCut / 100.0;  //Laugh.
    cout << timeRevert << endl;  //Watch heads explode.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM