使用 IF 语句比较两个整数

comparing two integers using IF statement

本文关键字:两个 整数 IF 语句 比较 使用      更新时间:2023-10-16

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

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

如果第一个整数高于第二个整数,程序会跳到末尾,我的问题是它不会更新"mins"。 提前致谢

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

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相等,则输出不正确。

更正留给读者作为练习。

这是错误的

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;

您可以使用 shortland if/else:

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

编写一个 if 语句来比较这两个值并更新 步骤 1 中的变量(如果您这样做,则不会有任何"其他" 正确

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

#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

因此,在答案中呈现的代码中,只有我的代码正确执行:)