我需要幫助調試我的代碼。所以我製作了一個程序,可以對數字進行加減,但是當我實現一個do-while循環來重放程序時,實際的程序會關閉,並且不會執行do-while循環,也不會重播程序。他們的代碼有問題嗎?C++程序故障?
P.S.我也使用的代碼塊IDE的int again;
#include <iostream>
using namespace std;
int main()
{
// Addition and Subtraction Calculator
int a_number, number1, number2, sum, number3, number4, subsum, again;
// subsum = subtracted sum
// number1 and number2 are variables that hold the users input for addition
// number3 and number4 are variables that hold the users input for subtraction
do
{
cout << "Addition & Subtraction Calculator" << endl;
cout << "-------------------------------------------" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;
while (a_number < 1 || a_number > 2)
{
cout << "Please enter either 1 or 2" << endl;
cin >> a_number;
}
switch (a_number)
{
case 1:
cout << "Please enter a number" << endl;
cin >> number1;
cout << "Please enter another number" << endl;
cin >> number2;
sum = (number1 + number2);
cout << "The sum is " << sum << endl;
break;
case 2:
cout << "Please enter a number" << endl;
cin >> number3;
cout << "Please enter another number" << endl;
cin >> number4;
subsum = (number3 - number4);
cout << "The answer to the subtraction problem is: " << subsum << endl;
break;
}
cout << "Do you want to try again? [y/n]" << endl;
cin >> again;
}
while (again == 'y' || again == 'n');
return 0;
}
你能否正確縮進你的代碼? – yizzlez
你嘗試過使用調試器嗎? – Amit
'cin >> again;'你再次知道'是一個'int',對吧?那麼......當你輸入'y'或'n'而不是一個有效的'int'時,你到底會發生什麼? – WhozCraig