【发布时间】:2015-02-24 21:00:55
【问题描述】:
如何让编译器同时检查语句的左侧和右侧?如果我没记错的话,我认为在 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;
}
我遇到的这个问题是,它只读取左侧,因此事务只返回 1。
感谢您的宝贵时间!
编辑
https://ideone.com/S66lXi (account.cpp)
https://ideone.com/NtwW85 (main.cpp)
【问题讨论】:
-
我认为 C 也支持短路评估,就像 C++ 一样。 en.wikipedia.org/wiki/Short-circuit_evaluation
-
他们不是只评估一侧,他们先评估左边的语句,如果结果可以确定,他们不评估右边的语句。例如,
T || anything始终为真,因此如果||运算符的左手为真,则无需评估该运算符的右手。F && anything也一样。但是,例如,如果您有T && something,则在您评估右侧之前,结果是未知的。 -
@triple_r 这很有意义。我根本不这么看。谢谢
标签: c++ if-statement operand