2014-10-06 77 views
1

我有两个输入,唯一的区别是我在第二个输入中将“double”替换为“float”。然而,第一个可以按预期运行,但不是第二个。第二个不会以0.1的输入结束。任何人对此有一些想法?非常感谢!在这个输入中float和double有什么区别?

第一输入:

#include <iostream> 

using namespace std; 

int main() 
{ 
    double input; 
    input = 0; 
    double sum = 0; 
    cout << "Please enter a series numbers and end with 0.1: "; 
    cin >> input; 
    while (input != 0.1) 
    { 
     sum += input; 
     cout << "The cumulative sum is: " << sum << endl; 
     cin >> input; 
    } 
    return 0; 
} 


Please enter a series numbers and end with 0.1: 1 2 3 0.1 
The cumulative sum is: 1 
The cumulative sum is: 3 
The cumulative sum is: 6 

第二输入:

#include <iostream> 
using namespace std; 

int main() 
{ 
    float input; 
    input = 0; 
    float sum = 0; 
    cout << "Please enter a series numbers and end with 0.1: "; 
    cin >> input; 
    while (input != 0.1) 
    { 
     sum += input; 
     cout << "The cumulative sum is: " << sum << endl; 
     cin >> input; 
    } 
    return 0; 
} 


Please enter a series numbers and end with 0.1: 1 2 3 0.1 
The cumulative sum is: 1 
The cumulative sum is: 3 
The cumulative sum is: 6 
The cumulative sum is: 6.1 
+0

另一种方法是说“以'end'结尾'”或任何其他文本,并且让你的循环条件为'while(cin)'(或者甚至更好,while(cin >> input))并且摆脱另外两个'cin >> input'的重复实例)。如果他们输入的东西不是有效的浮点数,那么循环将结束。 – 2014-10-06 06:35:18

回答

6

在条件(input != 0.1)0.1最接近理性1/10 double。最接近这个理性的float表示一个不同的值,并且不会使这个条件成立。

如果要在程序中使用float,请使用(input != 0.1f)作为相应的条件。

+6

而且一般来说,不应该为浮点数进行比较。见http://stackoverflow.com/questions/588004/is-floating-point-math-broken – o11c 2014-10-06 05:40:09

+0

@ o11c我同意你! – 2014-10-06 06:16:05

+1

@ o11c我一直比较浮点数的相等性。 – 2014-10-06 06:19:02

1

你必须明确地投0.1float,如:

while(input != (float)0.1) 

最好是在比较浮点数使用显式转换。

+0

比较两个浮点数是危险的,如果不是现在这将是7年。 – 2014-10-06 06:15:25

+0

不仅如此,没有必要施展一个常数。只需附加一个'f'即可。 – Yamakuzure 2014-10-06 06:45:27

+2

虽然它适用于0.1,但通常不能保证将双字面转换为浮点数会使浮点数接近文字的名义值。有两个例外,从小数到双精度,从双精度到浮点精度,引入了附加舍入误差。 – 2014-10-06 12:46:25