Xia*_*ang 1 c++ floating-point double
我有两个输入,唯一的区别是我在第二个输入中用"float"替换"double".但是,第一个可以按预期运行,但不能运行第二个.第二个不以0.1的输入结束.有谁对此有一些想法?非常感谢!
第一输入:
#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
Run Code Online (Sandbox Code Playgroud)
第二输入:
#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
Run Code Online (Sandbox Code Playgroud)
0.1
在条件(input != 0.1)
是double
最接近理性1/10.在float
最接近这种理性的,0.1f
代表不同的值,并且不使这一情况属实.
如果要float
在程序中使用,请使用(input != 0.1f)
相应的条件.