从数组中查找5个数字的最高、最低和平均值的程序

Program that finds Highest, Lowest, and Average of 5 number from an Array

本文关键字:平均值 程序 数组 查找 5个 数字      更新时间:2023-10-16

我的作业是写一个程序,找出用户输入的数组中5个数字的最大值、最小值和平均值。这是我的问题,用户不需要输入所有5个数字。但必须至少输入2个数字。

我已经完成了整个程序,我在开始时遇到了问题,下面是我遇到问题的代码:

// Ask for name and explain program
cout << "Please enter your name: ";
cin >> name;
cout << endl;
cout << "Hi " << name << ", please enter up to 5 whole numbers." << endl;
cout << "I will find the HIGHEST, LOWEST, and AVERAGE number." << endl;
// Loop through users input
for (int i = 0; i < SIZE; i++)
{
    cout << "Enter number " << (i + 1) << " : ";
    cin >> number[i];
    // Validate that the user has entered atleast 2 numbers
    if (i >= 1 && i < 4)
    {
        cout << "Do you wish to enter another number (Y/N)? : ";
        cin >> continue_game;
        // Validate that the user only enters Y/N
        while (continue_game != 'Y' && continue_game != 'y' && continue_game != 'N' && continue_game != 'n')
        {
            cout << "Please type in (Y/N): ";
            cin >> continue_game;
        }
        // What happens if user chooses NO
        if (continue_game == 'N' || continue_game == 'n') 
        {
            i = 5;
        }
        // What happens if user chooses YES
        else if (continue_game == 'Y' || continue_game == 'y')
        {
            i = i;
        }
    }
}

问题:如果用户在第二个数字之后按no,其余元素会得到一个分配给它们的数字,如:-8251616。有什么方法可以确保元素被分配为零或保持空白,请帮助它明天到期,我不能弄清楚。

SIZE = 5

当用户说不时,不要设置i = 5。只要用break;语句结束循环。

同样,在yes的情况下,i = i;语句是无用的。

当您获得最高值、最低值和平均值时,请确保您只查看从0i-1的值,这样您就不会访问数组中未初始化的元素。

如果你真的想要0,你需要用0填充数组:

int number[5] = {};

int number[5];
for (int i = 0; i < 5; ++i) {
    number[i] = 0;
}

但是,如果用户输入的数字少于5个,则会给出错误的输出。您应该做的是计算用户输入的数字数量,然后使用从0count - 1的值。

建议,用break;代替i = 5;