2016-08-04 70 views
-1

我不知道爲什麼當我執行這個程序時浮動不能打印確切的值的原因。浮動不能正常工作

#include <iostream> 
using namespace std; 

int main(){ 

int a, b; 
float x; 

cout << "Input the value for a: "; 
cin >> a; 
cout << "Input the value for b: "; 
cin >> b; 

x = - b/a; 

printf("The value of x is: %.2f",x); 
//cout << "The value of x is: " << x; 

}

我想至少在我的輸入2和10 b的結果應該是0.20, 程序顯示0.00只

回答

3

你需要投你的操作數爲彩車。

ex: x = (float)a/(float)b 

看看這裏的更多信息:

你期待我想所有輸出的

Dividing two integers to produce a float result

+0

不會給出商。所以結果仍然是5 – jonju

+0

所以我不能得到浮動答案像1.5如果我的操作數是整數? – Marr

0

首先是錯誤的。

應該-5.00 -10/2 = -5。並用%.2f =>-5.00

假設。如果a = 10和b = 2,那麼按照你的代碼

`x= - 2/10` 

這應該給

x = 0. Notice the `\`. 

既然你與%.2f打印出來它給0.00該系統給出。

我希望這能澄清你的疑問。

+0

是這就是結果,但我想看到的是像0.20的excact答案是否有任何我應該添加打印出excact值? – Marr

+0

你可以通過@King得到它Arthur的答案通過類型轉換來浮動 – jonju