2015-08-08 111 views
0

我需要幫助調試我的代碼。所以我製作了一個程序,可以對數字進行加減,但是當我實現一個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; 
} 
+1

你能否正確縮進你的代碼? – yizzlez

+3

你嘗試過使用調試器嗎? – Amit

+1

'cin >> again;'你再次知道'是一個'int',對吧?那麼......當你輸入'y'或'n'而不是一個有效的'int'時,你到底會發生什麼? – WhozCraig

回答

0

使用char again;,而不是在你的代碼againint當在(again == 'y' || again == 'n')你有char比較again(一int),這沒有任何意義

0

您需要將再次變量更改爲char數據類型,因爲您需要存儲文本。事情是這樣的:

char again; 

您還需要while語句更改爲:

while(again != "n"); 

或者

while(again == "y"); 
1

確定。所以OP在使用int,他們應該使用char。這涵蓋了眼前的問題。 int again應該是char again

但有一個重要的點,其他答案已經錯過。

int again; 
cin >> again; 

用戶輸入將被轉換爲again所要求的整數。輸入y或n無法轉換爲整數,因爲y和n都不是數字,也不能轉換。 again保持不變,保持發生在內存中發生的任何垃圾值,並且實際上可能是y或n,但更重要的是,cin現在處於錯誤狀態,需要在繼續之前清除。

cin如果已經過測試,會通知OP。所以我們來測試它。

int again; 
if (cin >> again) 
{ 
    // got good input. Do something with it. 
} 
else 
{ 
    // got bad input. 
    cin.clear(); 
    // that bad input is still in the buffer and needs to be removed 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    // the above line will wipe out everything to the end of the stream or 
    // end of line, whichever comes first. 
} 

爲什麼這是很重要的:因爲OP是做了很多的數字輸入與cin並且它都沒有進行有效性檢查。例如:

cout << "Please enter a number [1 or 2]" << endl; 
cin >> a_number; 

如果用戶鍵入除數字之外的任何內容,程序就會完全中斷並且無法在沒有終止信號的情況下退出。

總是檢查錯誤狀態並返回代碼。他們在那裏幫忙。在使用前始終驗證用戶輸入。用戶是邪惡的,並會嘗試打破你的計劃。不要讓他們。