老師說每當c變數為負時:“變數a 為負”,但這沒有意義。
程式是否以錯誤的形式撰寫?
在我看來 else 應該是if(a>0)with 的一部分{}。我不知道他為什么選擇不使用它。
總之,正確的形式是:if(a>0){...}elseand than cout?
#include <iostream>`
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive";
else
cout << "the number a is negative";
}
uj5u.com熱心網友回復:
你的老師是對的。else適用于最新的if,因此 的值c決定了輸出。(更具體地說,程式只會在a和b都為正時列印一些東西。)您可以通過運行程式來測驗這一點。
輸出“數字 a 為負”是不合邏輯的,因為這就是測驗的重點。程式故意寫錯了。如果所有測驗問題的答案都是顯而易見的,那么每個人都會得到最好的成績。
uj5u.com熱心網友回復:
您需要使用curly brackets否則else將僅適用于newest if. 只有print當a和b都是時,程式才會positive。
uj5u.com熱心網友回復:
這里的核心問題是缺乏對程式應該做什么的明確規范。我懷疑您確實擁有它,但如果沒有它,我只能解釋代碼在做什么,以及如何將老師的引述解讀為描述代碼的作用。
在這里可視化是您的代碼的修改版本,這是不言自明的(我希望):
#include <iostream>
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive"; // true
else
cout << "the number 'c' is negative or zero, 'a' and 'b' are positive";
else
cout << "the number 'b' is negative or zero , 'a' is positive, no idea about 'c'";
else
cout << "the number 'a' is negative or zero , no idea about 'b' and 'c'";
}
我懷疑這個輸出“不知道”的地方是您可能想要使用更多ifs 的地方,以便描述其他數字。
注意:我堅持你的風格(沒有{})。但我建議慷慨地使用它們。根據我的經驗,它讓生活更輕松,在我看來,它使代碼更具可讀性。
我覺得老師的話
每當 c 值為負時,它就會說:“ a 數為負”,但這沒有意義
應讀作:
'每當 c 值為負(并且其他兩個為正)時,此代碼輸出:“'a' 數為負”,但這沒有意義,因為a當發生此輸出時實際上是正數。
并且我同意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335817.html
