![](/img/trans.png)
[英]How do i get the total number of integers entered into an array returned from a function in C++, as well as the lowest highest and average scores?
[英]Program that finds Highest, Lowest, and Average of 5 number from an Array
我的作业是编写一个程序,找出用户输入的 Array 中 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。 有什么方法可以确保元素被分配为零或保持空白,请帮助明天到期,我无法弄清楚。
尺寸 = 5
当用户说不时,不要设置i = 5
。 只需以break;
结束循环break;
陈述。
另外, i = i;
是的情况下的陈述是无用的。
当您获得最高、最低和平均值时,请确保您只查看从0
到i-1
的值,这样您就不会访问数组的未初始化元素。
如果你真的想要零,你需要用零填充数组:
int number[5] = {};
或者
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
但是,如果用户输入的数字少于 5 个,这将给出错误的输出。 您应该做的是计算用户输入的数字数量,然后使用从0
到count - 1
。
忠告,使用break;
而不是i = 5;
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.