c ++读取左右if语句条件

c++ Reading both left AND right if statement conditions

如何让编译器同时检查语句的左侧和右侧?如果我没记错的话,我认为在 C 语言中,如果你有 &&||,它会向左和向右读取......所以当我查找 C++ 时,它说只检查如果左边是真的....我需要的是能够检查两边是否都是真的。

所以:

//Transactions has been initialized to 0

1. if deposit OR withdraw are greater than or equal to 1, add 1 to variable transactions.
2. if deposit AND withdraw are BOTH greater than or equal 1, then add 2 to variable transactions.
3. else if BOTH are less than 1, transaction is 0.

    if (deposit >= 1 || withdraw >=1)
        {
            transactions = transactions + 1;
            cout << "Transactions:  " << transactions << endl;
        }

    else if (deposit >= 1 && withdraw >=1)
        {
           transactions = transactions + 2;
           cout << "Transactions:  " << transactions << endl;
        }
    else
        {
            cout <<"Transactions: " << transactions << endl;
        }

我遇到的这个问题是,它只读取左侧,因此只进行交易 returns 1.

感谢您的宝贵时间!

编辑

https://ideone.com/S66lXi (account.cpp)

https://ideone.com/NtwW85 (main.cpp)

&& 条件放在第一位,然后将 || 条件作为 else if.

zenith 提供的解释(如果对您有帮助,请在评论中+1):

The most restrictive case needs to go first, since if A && B is true, A || B will always be true anyway. And thus if you put && after ||, the || case will catch whenever the && case is true.

此外,另一个注意事项:将 cout 留在所有括号外,您可以删除 else。无论如何都会打印出来,所以不需要输入 3 次。

你对 C 的看法不对。|| "logical or" 运算符在一侧为真时立即终止,并开始从左到右求值。

然而,这与这里无关。尽可能使用德摩根定律将 || 转换为 (not) and

您可以按以下方式重写 if 语句

if (deposit >= 1 && withdraw >=1)
    {
       transactions = transactions + 2;
       cout << "Transactions:  " << transactions << endl;
    }
else if (deposit >= 1 || withdraw >=1)
    {
        transactions = transactions + 1;
        cout << "Transactions:  " << transactions << endl;
    }

else
    {
        cout <<"Transactions: " << transactions << endl;
    }

另一种方法是使用下面的表达式

int condition = ( deposit >= 1 ) + ( withdraw >=1 )

if ( condition == 2 )
    {
       transactions = transactions + 2;
       cout << "Transactions:  " << transactions << endl;
    }
else if ( condition == 1 )
    {
        transactions = transactions + 1;
        cout << "Transactions:  " << transactions << endl;
    }

else
    {
        cout <<"Transactions: " << transactions << endl;
    }

或者干脆

 int condition = ( deposit >= 1 ) + ( withdraw >=1 )

 transactions = transactions + condition;
 cout << "Transactions:  " << transactions << endl;

或者

 int condition = ( deposit >= 1 ) + ( withdraw >=1 )

 transactions += condition;
 cout << "Transactions:  " << transactions << endl;

由于要求 1 && 2 都可以评估为真,因此您应该从代码中取出嵌套的 if/else 选择语句。不幸的是,上面 vlad 的一段优雅代码不能准确地满足要求。由于要求 1 和 2 都可以评估为真,事务应该能够等于 3。

下面的代码准确地满足了您提出的要求。

if (deposit >=1 || withdraw >=1)
    ++transactions;

if (deposit >=1 && withdraw >=1)
    transactions += 2;

if (deposit < 1 && withdraw < 1)
    transactions = 0;

cout << "transactions: " << transactions;