【问题标题】:comparing two integers using IF statement使用 IF 语句比较两个整数
【发布时间】:2018-03-29 08:58:09
【问题描述】:

嗨,我正在尝试使用 if 语句解决练习问题,找到两个整数之间的最小值。说明是

  1. 声明要存储最小值的变量(例如“min”)
  2. 声明两个变量,要求用户输入两个整数并将它们保存到这些变量中
  3. 假设第一个整数是最小值并将其保存到步骤 1 中声明的“min”变量中
  4. 编写一个 if 语句,比较这两个值并从第 1 步更新变量(如果操作正确,则不会有任何“else”)

这是我的代码

#include <iostream>
using namespace std;

int main ()
{
int mins,a,b;
cout << "Enter two integers: ";
cin >> a >> b;
mins = a;
if (a<b)
    {
    cout << "The minimum of the two is " << mins;
    }
else

return 0;

如果第一个整数大于第二个整数,程序会跳转到末尾,我的问题是它没有更新“分钟”。提前致谢

【问题讨论】:

  • if (a
  • 您写了mins = a;,但这并不总是正确的。您已经有针对这种情况的案例。只需在正确的情况下为 mins 分配正确的值。
  • 您缺少else 子句的内容。

标签: c++ if-statement min


【解决方案1】:

您的程序逻辑错误。你想要这个:

int main()
{
  int mins, a, b;
  cout << "Enter two integers: ";
  cin >> a >> b;

  if (a < b)
    mins = a;
  else
    mins = b;

  cout << "The minimum of the two is " << mins << endl;

  return 0;
}

现在这仍然不完全正确,因为如果 ab 相等,则输出不正确。

更正留给读者作为练习。

【讨论】:

  • 我建议将换行符或endl 添加到最后的cout,以刷新缓冲区。 :-)
  • @ThomasMatthews 为什么? std::cout 的析构函数已经这样做了。
  • @nwp 也许是因为 SamD 很高兴在程序意外终止之前看到消息刷新到输出流。
  • @nwp -- 因为,正式地,写入输出设备的一行文本必须以换行符结尾。如果不显示,则保证显示。
  • @nwp -- 我没有说它不会被刷新。但对于基本问题,请参阅 C11 标准 7.21.2/2:“从文本流中读取的数据必须与之前写入该流中的数据进行比较,前提是:...最后一个字符是换行符。”
【解决方案2】:

编写一个 if 语句,比较这两个值并更新 来自 step1 的变量(如果你这样做,就不会有任何“其他” 正确

我认为您需要的是以下内容。

#include <iostream>
using namespace std;

int main()
{
    int min;                   // Step 1
    int a, b;                  // Step 2

    cout << "Enter two integers: ";

    cin >> a >> b;

    min = a;                   // Step 3
    if ( b < a ) min = b;      // Step 4

    cout << "The minimum of the two is " << min << endl;

    return 0;
}

程序输出可能看起来像

Enter two integers: 3 2
The minimum of the two is 2

因此,在答案中提供的代码中,只有我的代码正确。:)

【讨论】:

    【解决方案3】:

    这是错误的

    mins = a;
    if (a<b)
    {
    cout << "The minimum of the two is " << mins;
    }
    else
    

    应该是的。

    if (a < b){
      mins = a;
    }
    else{
      mins = b;
    }
    cout << "The minimum of the two is " << mins;
    

    【讨论】:

      【解决方案4】:

      if/else 可以使用shortland:

      #include <iostream>
      #include <algorithm>
      
      int main() {
          int a, b;
          std::cout << "Enter a and b: ";
          std::cin >> a >> b;
          int min = (a>b) ? b : a;
          std::cout << "The min element is: " << min;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-05-09
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2013-10-21
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多