注意:我是初學者。 如果用戶輸入的標記超過 200,我使用 goto 陳述句執行,但如果用戶輸入的標記小于 100,那么其余代碼應該運行。我怎樣才能做到這一點 ?
這是一段代碼
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
float sum, perc;
int total = 500;
INPUT:
cout << "Enter marks for English" << endl;
cin >> a;
cout << "Enter marks for Urdu" << endl;
cin >> b;
cout << "Enter marks for Maths" << endl;
cin >> c;
cout << "Enter marks for Computer" << endl;
cin >> d;
cout << "Enter marks for Islamiat" << endl;
cin >> e;
if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
cout << "You must enter all subject marks below 100" << endl;
}
goto INPUT;
sum = a b c d e;
perc = (sum / total) * 100;
if (a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100) {
cout << "Percentage is = " << perc << "%" << endl;
}
else {
cout << "You must enter marks below 100" << endl;
return 0;
}
if (perc >= 50) {
cout << "Congratulations you are Passed" << endl;
}
else {
cout << "You are fail" << endl;
}
return 0;
}
uj5u.com熱心網友回復:
正如評論部分已經指出的那樣,該行
if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
是錯的。僅當所有輸入的分數都高于 100 時,整個if條件才會為真,但如果至少有一個輸入的分數高于 100,則您希望條件為真。您可以通過使用(邏輯 OR) 而不是(邏輯與)。if||&&
另一個問題是goto,如果您可以使用回圈輕松完成相同的事情,那么通常應該避免使用。有關詳細資訊,請參閱以下問題:使用 goto 有什么問題?
另一個答案goto通過使用do...while回圈來避免。它通過引入一個附加變數并在每次回圈迭代中多次檢查該變數來實作這一點。但是,如果您使用帶有顯式break陳述句的無限回圈,則無需引入必須多次檢查的附加變數:
//loop forever until input is ok
while ( true )
{
cout << "Enter marks for English: " << endl;
cin >> a;
cout << "Enter marks for Urdu: " << endl;
cin >> b;
cout << "Enter marks for Maths: " << endl;
cin >> c;
cout << "Enter marks for Computer: " << endl;
cin >> d;
cout << "Enter marks for Islamiat: " << endl;
cin >> e;
//check whether input is ok
if ( a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100 )
//input is ok, so we can break out of the infinite loop
break;
//input is not ok, so we must print an error message and repeat the loop
cout << "You must enter all subject marks at or below 100\n" << endl;
}
uj5u.com熱心網友回復:
只需使用 do-while 回圈,例如
bool success = false;
do
{
cout << "Enter marks for English" << endl;
cin >> a;
cout << "Enter marks for Urdu" << endl;
cin >> b;
cout << "Enter marks for Maths" << endl;
cin >> c;
cout << "Enter marks for Computer" << endl;
cin >> d;
cout << "Enter marks for Islamiat" << endl;
cin >> e;
success = not ( a > 100 || b > 100 || c > 100 || d > 100 || e > 100 );
if ( not success )
{
cout << "You must enter all subject marks below 100" << endl;
}
} while ( not success );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425958.html
