这里有很新的编程,我有一个任务,我需要实现以下目标:
到目前为止,我已经写过:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
获取他们的名字后,只有while循环中的最后一个cout
似乎先执行,然后从顶部开始,依此类推,直到for
循环到达终点,具体取决于{{1 }}。我知道我在这里遗漏了一些东西,可能是按照操作的顺序以及我执行循环的方式,但我无法看到它。你们这些有这种语言经验的人能不能给我任何关于这里发生了什么以及如何解决这个问题的建议?谢谢。
答案 0 :(得分:0)
在while
群组内,您只想使用cout
行一次(开头看起来不错)。
您的第一次检查应该是针对==-100
或类似的,因为现在,如果您输入-100
,您将会收到“仅输入0到100分的分数”消息。
每次使用cin.ignore();
后,您都应该保持cin >> VARIABLE
来电,此后您将删除EoL角色。
示例代码:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
您的一些变量也需要将移到 for
循环中。
此外,我将personScoreCounter
的限制更改为[0:4]而不是[1:5] - 这样您就可以更轻松地将其用于平均。
答案 1 :(得分:0)
您也可以尝试使用cin.getline()而不是getline(std :: cin,...):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
这也允许输入中的空格。 http://www.cplusplus.com/reference/istream/istream/getline/