C++ Primer Plus第7章第2道练习题:
要求用户输入最多10个高尔夫乘积,并将其存储在一个数组中。程序允许用户提早结束输入,并在一行显示所有成绩,然后报告平均成绩。请使用3个数组处理函数,分别进行输入、显示和计算平均成绩。
问题描述:
当输入10个float时,enterScore()为什么还能返回一个float值。我使用Visual Studio的调试器,逐条语句地看了一遍程序的执行情况,发现输入最后一个值的时候,没有执行return语句。请问大神是什么情况?
以下是我的代码:
#include <iostream>
using namespace std;
const int SIZE = 10;
int enterScore(float score[], const int SIZE);
float calculateScore(const float score[], const int SIZE);
void displayScore(const float score[], const int SIZE, float average);
int main()
{
float score[SIZE];
int count;
float average;
count = enterScore(score, SIZE);
average = calculateScore(score, count);
displayScore(score, count, average);
return 0;
}
int enterScore(float score[], const int SIZE)
{
cout << "Enter the scores in this match (q to quit): \n";
for (int count = 0; count < SIZE; count++)
{
cout << "Score " << count + 1 << ": ";
if (!(cin >> score[count]))
return count;
}
}
float calculateScore(const float score[], const int SIZE)
{
float total = 0.0f;
for (int count = 0; count < SIZE; count++)
total += score[count];
return total / SIZE;
}
void displayScore(const float score[], const int SIZE, float average)
{
cout << "There are scores and average.\n"
<< "Scores: ";
for (int count = 0; count < SIZE; count++)
cout << score[count] << " ";
cout << "\nAverage: " << average << endl;
}
enterScore
函数有问题。cin >> score[count]
正常情况下总返回true
,所以return count;
不会执行。可把函数改成: