使用if代码确定最大值和最小值
determines the largest and smallest just with if code
我想写一个程序,确定从用户那里收到的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&;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;
}
相关文章:
- 最大和最小 1 C++函数
- txt 文件中浮点数的最大和最小值
- 为什么我的C 代码无法计算整数的最大和最小值
- 函数读取最大和min int值,并用文本字符串返回
- 在C弦C 中收集最大和最小的数字
- 在数组C 中排序最大和最小的值
- 在数组中找到最大和最小的数字
- 查找序列中最大和最小的 2 个整数
- 在C++中使用 for 循环从用户输入中查找最大和最小整数
- 如何获得C 中向量复合物值的最大,最小和位置
- 我试图显示我输入的三个值中最大和最小的数量
- 给定有向图和商店位置,放置商店,使从任何城市到最近商店的最大距离最小化
- 我无法弄清楚如何在不使用 climits 的情况下计算最大和最小有符号数C++
- 使用 c++ 在值数组中查找最大利润(最大 - 最小值)
- 所有最接近的较小值
- 如何查找向量中元素的最大和最小索引
- C++数组从最大到最小的数字
- 程序可以在不使用数组的情况下找到5个数字中最大和最小的
- 如何用最少的比较得到3个值中的最大和最小值
- C++的平均、最大和最小赋值