如何让编译器检查语句的左侧和右侧?如果我没有弄错的话,我认为在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)
答案 0 :(得分:8)
首先设置&&
条件,然后将||
条件设为else if
。
一种解释,由天顶提供(如果这有助于你,则在评论中给他+1):
最严格的情况需要先行,因为如果是
A && B
无论如何,true
,A || B
始终为true
。因此,如果你把 在&&
之后的||
,只要||
案例发生,&&
案件就会抓住true
。
另外,另请注意:将cout
留在所有括号之外,您可以删除else
。无论如何都要打印它,所以不需要打三次。
答案 1 :(得分:4)
你对C不正确。||
&#34;逻辑或&#34;一旦一方成立,操作员就会终止,并开始从左到右进行评估。
然而,这与此无关。使用De Morgan定律尽可能将||
转换为(not) and
。
答案 2 :(得分:3)
您可以通过以下方式重写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;
答案 3 :(得分:1)
既然要求1&amp;&amp; 2可以评估为true,你应该从代码中取出嵌套的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;