2009-09-10 71 views
2
#include <iostream> 
using namespace std; 
int main() 
{ 
     float s; 
     s = 10/3; 
     cout << s << endl; 
     cout.precision(4); 
     cout << s << endl; 
     return 0; 

} 

为什么输出不显示3.333但只有3?C++ Cout浮点数问题

回答

7

,因为你正在做s = 10/3

整数除法尝试

s = 10.0f/3.0f 
+0

关闭,但现在是双倍的。 – GManNickG 2009-09-10 21:29:20

+0

现在怎么样? – jcopenha 2009-09-10 21:33:07

+0

右键。 :P [15chars] – GManNickG 2009-09-10 21:33:30

2

10/3是整数除法。您需要使用10.0/3(浮动)10/3或10/3.0等

+0

使用C++类型转换,如'static_cast' – GManNickG 2009-09-10 21:30:51

+0

或ctor语法,如'float(3)' – MSalters 2009-09-11 10:08:36

4

做一个恒定的浮动师正确的方法是:

s = 10.f/3.f; // one of the operands must be a float 

没有f后缀,你是做double师,发出警告(从floatdouble)。

您也可以施放一个操作数:

s = static_cast<float>(10)/3; // use static_cast, not C-style casts 

在正确分割了。