使用if代码确定最大值和最小值

determines the largest and smallest just with if code

本文关键字:最大值 最小值 if 代码 使用      更新时间:2024-04-28

我想写一个程序,确定从用户那里收到的5个数字中最小和最大的一个,但我只确定了最小的,我觉得这也是错误的,我只能用if命令来确定。。。谢谢你帮助我的朋友

#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
cout << "Enter 5 integers in a b c d et:t";
cin >> a >> b >> c >> d >> e;
if (a < b && c && d && e)
cout << "smallest number is a";
if (b < a && c && d && e)
cout << "smallest number is b";
if (c < b && a && d && e)
cout << "smallest number is c";
if (d < b && c && a && e)
cout << "smallest number is d";
if (e < b && c && d && a)
cout << "smallest number is e";
return 0;
}

我认为您仍然需要指定要测试的内容,以便在if语句中使用较小的数字,如

if (a < b && a < c && a < d && a < e)
{
cout << "The smallest number is " + a;
}

然后要找到最大的,你可以用同样的方法,但当然要使用>b&amp;a>c

FYI,我修改了一个优化的代码,它在时间复杂性方面更有效。

#include <iostream>
using namespace std;
int main()
{
cout << "Enter 5 integers in a b c d et:t";
int total = 5;
int max, min, a;
cin >> a;
max = min = a;
while (total-- >= 2) {
cin >> a;
if (a > max) {
max = a;
}
if (a < min) {
min = a;
}
}
cout << "smallest number is " << min << endl;
cout << "biggest number is " << max << endl;
return 0;
}