2013-03-03 62 views
1

我試圖將我的最終答案舍入爲2位小數,所以它是美元和美分。我是編碼新手,無法弄清楚。我要舍「W」中,說:「你需要充電量」行這裏是我的代碼:期待圍繞2位小數的最終答案C++

#include <iostream> 

using namespace std; 

int main() 
{ 
    string Choice; 


    float x, w; 

    cout << "Please enter the amount needed." << endl; 
    cin >> x; 


    w = x/(1-0.0275); 

    cout << "The amount you need to charge is $"<< w << "." << endl; 

    return (0); 

} 
+1

http://www.cplusplus.com/forum/beginner/3600/? – 2013-03-03 18:25:26

+3

您無法精確地用浮點數表示大多數小數。使用整數並使用便士來計算。 – 2013-03-03 18:28:03

回答

4

據這裏的例子http://www.cplusplus.com/forum/beginner/3600/ 你可以使用

cout << setprecision(2) << fixed << w << endl; 

fixed可選)

你將不得不#include <iomanip>

正如處Synxis指出,這將ONL Ÿ工作打印的價值,它不會改變通過w

+0

僅適用於打印。如果他想'w'只有兩位小數,他需要四捨五入(int(100 * w)/100.0)。 – Synxis 2013-03-03 18:31:28

+1

這是真的,但我想這是他需要的 – 2013-03-03 18:33:24

+0

有道理,因爲該線在返回語句之前。 – 2013-03-03 18:37:14

2

保存的值可以送花兒給人乘以你的答案x 100,圓形,然後再乘以100

x = (int)(x*100+0.5f); 
x = ((float)(x))/100.0; 
1

劃分你可以改變你的貨幣單位爲「美分」,然後除以100獲得美元和國防部100獲得美分。

unsigned int money = 152; // USD $1.52 

cout << "Money is: " << (money/100) << "." << (money % 100) << "\n"; 

這可能更準確。在網上搜索「一切都知道浮點」。