2016-08-04 71 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