新手:关于函数、循环和返回值的问题

新手上路,请多包涵

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;
}
阅读 1.6k
1 个回答

enterScore函数有问题。
cin >> score[count]正常情况下总返回true,所以return count;不会执行。

可把函数改成:

int enterScore(float score[], const int SIZE) {
    cout << "Enter the scores in this match (q to quit): \n";

    int count = 0;
    for (; count < SIZE; count++) {
        cout << "Score " << count + 1 << ": ";

        cin >> score[count];
    }

    return count;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题