【问题标题】:Comparing Integers C++ [closed]比较整数 C++ [关闭]
【发布时间】:2013-01-15 11:55:59
【问题描述】:

嘿,所以我这周刚开始学习基本的 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");

}

【问题讨论】:

  • 这更多是关于逻辑,而不是比较 C++ 中的内容。无论哪种方式,我认为 SO 不是问的地方。
  • nvm 我在下面看到答案

标签: c++


【解决方案1】:
#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;    
}

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

不鼓励以一种更神秘、更不可读的方式来做这件事

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

一个优雅的方式是#include &lt;algorithm&gt;

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

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

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

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      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;
      }
      

      另外注意,你应该写int main()而不是void main()

      【讨论】:

      • 感谢有关 int main() 的信息
      猜你喜欢
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多