条件操作者的最高 4 个数字

highest of 4 numbers by conditional operater

本文关键字:数字 操作者 条件      更新时间:2023-10-16
 #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;
}