比较整数 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14624814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:31:43  来源:igfitidea点击:

Comparing Integers C++

c++

提问by TAM

Hey So I am learning basic c++ just started this week, I have a question that says:

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

Write a program to compare 3 integers and print the largest, the program should ONLY Use 2 IF statements.

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

I am not sure how to do this so any help would be appreciated

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

So far I have this:

到目前为止,我有这个:

#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");

}

回答by billz

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;
}

Also note, you should write int main()instead of void main().

另请注意,您应该编写int main()而不是void main().

回答by legends2k

#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;    
}

Although the above code satisfies the exercise question, I thought I'll add a couple of other ways to show ways of doing it without any ifs.

虽然上面的代码满足了练习题,但我想我会添加一些其他的方法来展示没有任何ifs 的方法。

Doing it in a more cryptic, unreadable way, which is discouraged, would be

以一种更神秘、更不可读的方式来做,这是不鼓励的,将是

int max = (a < b) ? ((b < c)? c : b) : ((a < c)? c : a);

An elegant way would be to #include <algorithm>and

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

int max = std::max(std::max(a, b), c);

With C++11, you can even do

使用 C++11,你甚至可以做到

const int max = std::max({a, b, c}); 

回答by Ivan Kuckir

You don't need the last "else if" statement. In this part of code it is sure that "c" is maximal - no number is larger.

您不需要最后一个“else if”语句。在这部分代码中,可以确定“c”是最大的——没有更大的数字。

回答by Anton Kovalenko

Hint: one of your ifstatements is useless (actually, it introduces a bug because nothing will be printed if a, b and c are all equal).

提示:你的一个if语句是无用的(实际上,它引入了一个错误,因为如果 a、b 和 c 都相等,则不会打印任何内容)。