У меня есть два входа, и единственное отличие заключается в том, что я заменяю «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
Альтернативой является «конец с« концом »или любым другим текстом и сделать ваше условие цикла« while (cin) »(или даже лучше,« while (cin >> input) »и избавиться от два других дублирующих экземпляра 'cin >> input'). Если они вводят что-то, что не является допустимым float, тогда цикл завершится. –