我有兩個輸入,唯一的區別是我在第二個輸入中將「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
另一種方法是說「以'end'結尾'」或任何其他文本,並且讓你的循環條件爲'while(cin)'(或者甚至更好,while(cin >> input))並且擺脫另外兩個'cin >> input'的重複實例)。如果他們輸入的東西不是有效的浮點數,那麼循環將結束。 – 2014-10-06 06:35:18