如何使用 do while 循环确定最高值和最低值

How do I determine the highest and lowest value using do while loops

本文关键字:最高值 最低值 循环 何使用 do while      更新时间:2023-10-16

我目前被困在家庭作业中,问题是我需要创建一个程序,该程序将要求 5 个整数,我应该从中确定最高值和最低值。到目前为止,我很困惑,我的初始代码是这样的:

#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;

return 0;
}

任何帮助将不胜感激。提前感谢!

您应该将数字存储到std::vector<int>std::array中,然后使用 std::minmax_element 算法获取最大和最小的数字。

如果允许您使用std::maxstd::min,您可以使用:

max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});

以简化循环中的代码。

这将是我不使用数组的解决方案。 我建议你之前自己尝试一下。当你只是复制代码时,你不会学到东西。

#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}

如果你不需要记住,你可以循环例如5次,然后在询问下一个数字之前进行比较。

所以一般(想法,自己写并学习(:

对于(5次(
询问用户输入,如果最大数字为空,则另存为输入,如果最大数字较小,则等于输入,然后将输入

设置为最大数字

继续循环时间。

而不是每次都比较所有数字。只需将您当前的最小值与顺序中的数字进行比较即可。

int data[5];
// read numbers into data.
int min = data[0];   // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "n";

无需使用循环来执行此操作,您可以在没有它的情况下执行此操作 如果有必要使用循环,则必须使用数组或其他一些数据结构