条件操作者的最高 4 个数字
highest of 4 numbers by conditional operater
#include <iostream>
using namespace std;
int main()
{ int a,b,c,Highest;
cout<<"Enter three numbers:";
cin>>a>>b>>c;
Highest=(a>b&&a>c?a:b>c?b:c);
cout<<"Highest is:"<<Highest;
return 0;
}
我知道如何使用条件运算符找出 3 个数字中最大的一个。BUt 如何在 c+ 中使用条件运算符找出 4 个数字中的最大值 ???任何人都可以帮助我??
对我来说
,这个问题不是很好,作为学习如何做到这一点的一种方式。
相反,我会问如何找到三个数字中最高的一个 - 使用如何找到两个数字中最高的知识,然后在此基础上再接再厉。
正如@Some-程序员-伙计所指出的那样,这将使用中间结果:
int highest = a>b ? a : b;
highest = highest>c ? highest : c;
highest = highest>d ? highest : d;
或者,如果您想要并行性:
int hFirstPart = a>b ? a : b;
int hSecondPart = c>d ? c : d;
int highest = hFirstPart>hSecondPart? hFirstPart : hSecondPart;
将它们放入向量并使用std::max_element
:
std::vector<int> vec;
int tmp;
for(int i = 0; i < 3; ++i)
{
std::cin >> tmp;
vec.push_back(tmp);
}
int max = *std::max_element(vec.begin(), vec.end());
std::cout << max << std::endl;
Highest=(a>b&&a>c&&a>d?a:b>c&&b>d?b:c>d&c:d);
这段代码非常不可读,因此最好使用一组后续的if
子句对其进行扩展。
下面的代码适用于任意数量的元素,只需将 SIZE 替换为所需数量的元素即可。
#include <iostream>
using namespace std;
#define SIZE 4
int GetMax(int[], int, int, int);
int main()
{
int a[SIZE];
int i=0;
while(i < SIZE)
{
cout << "Enter input " << i+1 << " : ";
cin >> a[i++];
}
cout << "Highest = " << GetMax(a, 0, SIZE, a[0]) << endl;
return 0;
}
int GetMax(int a[], int i, int n, int max)
{
return ( i < n-1) ? GetMax(a, i+1, n, (a[i] > max ? a[i] : max)) : a[i] > max ? a[i] : max;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 条件操作者的最高 4 个数字