从数组中查找5个数字的最高、最低和平均值的程序
Program that finds Highest, Lowest, and Average of 5 number from an 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。有什么方法可以确保元素被分配为零或保持空白,请帮助它明天到期,我不能弄清楚。
SIZE = 5
当用户说不时,不要设置i = 5
。只要用break;
语句结束循环。
同样,在yes的情况下,i = i;
语句是无用的。
当您获得最高值、最低值和平均值时,请确保您只查看从0
到i-1
的值,这样您就不会访问数组中未初始化的元素。
如果你真的想要0,你需要用0填充数组:
int number[5] = {};
或
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
但是,如果用户输入的数字少于5个,则会给出错误的输出。您应该做的是计算用户输入的数字数量,然后使用从0
到count - 1
的值。
建议,用break;
代替i = 5;
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 计算数组c++的平均值
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- C 平均程序在循环时不计算n后不计算平均值
- C 程序总和从用户和显示平均值
- 如何将输入C 程序的平均值输入
- 用于计算平均值的C++程序
- 程序不会降低最低分数并在没有它的情况下计算平均值
- 编译三个文件以创建一个用于平均值的程序(取消注释?)
- C++,计算正数和负数并计算数字的平均值)编写一个读取未指定数量的整数的程序
- 编写一个程序,读取所有命令行参数并打印平均值 c++
- 一个求非常高的数的平均值的程序
- 用于查找最小值、最大值、平均值、中值和模式的程序