如何将多个变量与else if语句进行比较?

时间:2017-02-19 01:23:53

标签: c++

我是C ++的初学者。我从学校接到了一份功课,做了一些练习。其中之一是比较用户输入的3个变量,并在屏幕上打印程序,该数字更大或更小。问题是每次运行代码时,程序总是打印第一个输入的数字,即使它不符合条件。这是代码示例。我到处看,我无法理解什么是错的。

#include <iostream>

using namespace std;

int var1 = 0;
int var2 = 0;
int var3 = 0;

int main()
{
    cout << "Write 3 integer numbers" << endl;
    cin >> num1 >> num2 >> num3;

    if (var1 < var2,var3)
    {
        cout << num1 << " is smaller"<< endl;
    }

    else if (var2 < var1,var3)
    {
        cout << num2 << " is smaller"<< endl;
    }

    else if (var3 < var1,var2)
    {
        cout << num3 << " is smaller"<< endl;
    }

    system("pause");


}

1 个答案:

答案 0 :(得分:1)

从您的代码判断,我假设您想要找到最小的3个数字。但是,使用逗号是正确的方法,因为逗号是用于其他目的的操作数。

如果你想在一个if语句条件中比较多个变量,那么应该使用以下模板来完成它(它很乱,但我会解释它):

if ((variable_1 [operator] variable_2) [AND/OR/NOT operator] (variable_1 [operator] variable_3) ...)
  • variable_n其中n表示数字,表示可以在if语句中比较的变量。
  • [operator]表示可以使用的各种比较运算符,例如&lt;,&gt;,&lt; =等等......
  • [AND/OR/NOT operator]是运营商“||”,“&amp;&amp;”要么 ”!”使用过。
  • (...)表示您可以包含更多比较。

&&运算符(称为逻辑AND运算符)是您应该使用的运算符。使用此运算符,仅在“&amp;&amp;”两侧的两个比较时如果表达式返回true,则为true。它遵循以下语法:

(x > y) && (x > z) // Only if x is greater than y and z will the expression return true.

我已经为你修改了代码(除了if语句之外还有很多错误:

int main()
{
    // These variables don't have to be global for your case
    int var1 = 0;
    int var2 = 0;
    int var3 = 0;

    cout << "Write 3 integer numbers" << endl;
    cin >> var1 >> var2 >> var3; // You don't need num1, num2, num3.

    if ((var1 < var2) && (var1 < var3))
        cout << var1 << " is smaller"<< endl; // If there is only 1 statement in your if-condition, then curly braces are unrequired, just a styling tip I like.

    // I don't want to give the full solutions here, as this is your learning experience. Just fixed dome other errors in your code. You can use the first if-statement to do the other else-if statements.

    system("pause");
}

除了if语句之外,我还会指出代码中的其他错误:

  • 首先,为什么在主函数之外将var1var2var3声明为全局变量?这没错(代码即使是全局变量也能正常工作),但在你的情况下,它是不需要的。

  • 其次,您在if条件中比较变量var1var2var3。但是,它们设置为零,您可以输入3个完全不同的变量num1num2num3。这使var1var2var3保持不变,从而在0,0和0之间进行比较。您不需要num1num2num3

  • 第三,代码的逻辑本身容易出错,特别是当一些数字输入相同时。尝试输入(1,1,1)或(1,1,2)。我没有解决这个问题,因为它涉及到改变很多代码本身。

顺便说一句,如果你想知道逗号运算符是做什么的,我在下面解释了它:

[来源:运营商 - C ++教程] (http://www.cplusplus.com/doc/tutorial/operators/

逗号运算符(,)用于分隔多个表达式,这些表达式作为单个表达式的占位符。当评估表达式集以给出最终结果时,使用最右边的表达式。见这个例子:

int number, number2;
number2 = (number = 5, number += 7, number / 4);
cout << number2 << endl;

这里的作用是在此声明2个变量numbernumber2。在下一行中,number2是数字除以4,最初设置为5,然后递增7.第三行输出4,为(5 + 7)/ 4 = 3.

希望这会有所帮助。如果您需要任何进一步的解释,澄清或不明确的事情,请在帖子中告知我。祝你好运!