如何使用 do while 循环确定最高值和最低值
How do I determine the highest and lowest value using do while loops
我目前被困在家庭作业中,问题是我需要创建一个程序,该程序将要求 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::max
和std::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";
无需使用循环来执行此操作,您可以在没有它的情况下执行此操作 如果有必要使用循环,则必须使用数组或其他一些数据结构
相关文章:
- 如何使用 do while 循环确定最高值和最低值
- 如何使用指针找到最高值?
- 将迭代器设置为具有最高键的值
- 我无法显示包含整数最大值的索引. 但我可以显示数组中整数的最高值
- 为什么我的程序有时只能正确识别数组中的最高和最低值
- 需要帮助从数组中获取特定值并将它们从最高到最低排序
- 从OpenCV MLP响应中获取最高值(概率)位置
- C++ 查找无序树中具有最高值的节点
- C++矩阵-获取列数,其中最低值与后面列中最高值位于同一行
- 用于选择一组具有最高值总和的间隔的算法
- 我如何找出数组中的哪个元素具有最高值
- C++:在链表中查找类的最高值
- 返回具有最高值的数组的名称
- (c++)从txt文件中读取列中的数字数据并确定最高值
- 静态浮点变量仅存储分配的最高值;需要它来存储最新的
- 如何找到向量中最高值的索引,如果有两个"greatest"索引,则默认为较大的索引?
- 函数不返回输入到数组中的最高值和最低值
- 在结构和输出名称中查找最高值
- 从矢量中检索两个最高值
- 控制台应用程序-用户可以为c++中的整数变量输入的最高值是多少