比较整数C++

TAM*_*TAM 2 c++

嘿所以我本周刚开始学习基本的c ++,我有一个问题说:

编写一个程序来比较3个整数并打印最大的,程序应该只使用2个IF语句.

我不知道如何做到这一点所以任何帮助将不胜感激

到目前为止我有这个:

#include <iostream>

using namespace std;

void main()
{
int a, b, c;

cout << "Please enter three integers: ";
cin >> a >> b >> c;

if ( a > b && a > c) 
    cout << a;
else if ( b > c && b > a)
    cout << b;
else if (c > a && c > b)
    cout << b;

system("PAUSE");

}
Run Code Online (Sandbox Code Playgroud)

bil*_*llz 6

int main()
{
  int a, b, c;
  cout << "Please enter three integers: ";
  cin >> a >> b >> c;
  int big_int = a;

  if (a < b)
  {
      big_int = b;
  }

  if (big_int < c)
  {
    big_int = c;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

还要注意,你应该写int main()而不是void main().


leg*_*s2k 5

#include <iostream>

int main()
{
    int a, b, c;
    std::cout << "Please enter three integers: ";
    std::cin >> a >> b >> c;

    int max = a;
    if (max < b)
        max = b;
    if (max < c)
        max = c;

    std::cout << max;    
}
Run Code Online (Sandbox Code Playgroud)

尽管上面的代码满足了练习中的问题,但我认为我将添加其他两种方法来显示不带任何ifs的方法。

不鼓励以更隐秘,更难以理解的方式执行此操作

int max = (a < b) ? ((b < c)? c : b) : ((a < c)? c : a);
Run Code Online (Sandbox Code Playgroud)

一种优雅的方式将#include <algorithm>

int max = std::max(std::max(a, b), c);
Run Code Online (Sandbox Code Playgroud)

使用C ++ 11,您甚至可以

const int max = std::max({a, b, c}); 
Run Code Online (Sandbox Code Playgroud)