2017-03-03 28 views
-1

誰かがこのdo-whileループが正しく動作していない理由を説明できますか?なぜこのdo-whileループは動作しませんか?

プログラムが式を要求すると、プログラムは正しい答えを出力します。答えを表示した後、プログラムはユーザーに別の計算を実行するかどうかを尋ねます。しかし、ユーザーが計算をやり直したくないと示したとしても、プログラムはループします。

#include <iostream> 
#include <cmath> 
#include <string> 
using namespace std; 

int main() { 

    float num_one; 
    float num_two; 
    char user_operator_one; 
    char repeat; 

    cout << "This is a very simple calculator." << endl; 

    cout << "Please enter your expression: "; 
    cin >> num_one >> user_operator_one >> num_two; 
    cout << "\n\n"; 

    do 
     { 
      switch (user_operator_one) 
       { 
       case '+': 
        cout << num_one << "+" << num_two << "=" << num_one + num_two << endl; 
        break; 

       case '-': 
        cout << num_one << "-" << num_two << "=" << num_one - num_two << endl; 
        break; 

       case '*': 
        cout << num_one << "*" << num_two << "=" << num_one * num_two << endl; 
        break; 

       case '/': 
        if (num_two == 0) { 
         cout << "Answer is undefined" << endl; 
        } 
        cout << num_one << "/" << num_two << "=" << num_one/num_two << endl; 
        break; 

       default: 
        cout << user_operator_one << "is an unknown operation." << endl; 
        break; 
       } 

      cout << "Would you like to perform another operation (enter a 1 for yes, 0 for no.)"; 
      cin >> repeat; 
     } while (repeat == 1); 
} 
+0

char repeat; 

を変更することができます'1'や' 0'の代わりに 'y'や' n'を要求してみませんか? – Barmar

+0

また、この 'num_two == 0'のような2つのfloatを比較するのは良い考えではありません – Rama

+0

繰り返し問題を解決しても、表現。 – Barmar

答えて

4

repeatcharである、あなたは'1'に対してテストする必要があります

//... 
while (repeat == '1'); 

をそうしないと、ASCIIテーブルにSOHか」に相当する、1の小数値に対してテストしています見出し "の文字は印刷可能ではありません。

また、あなたがループの内部do部となる入力のためのあなたの要求を移動する必要があります。

do 
{ 
    cout << "Please enter your expression: "; 
    cin >> num_one >> user_operator_one >> num_two; 
    cout << "\n\n"; 
    // ... 
+2

または宣言を 'int'に変更してください。 – Barmar

+1

これが問題だった場合、プログラムはまったくループしませんか? – JGroven

+1

プロンプトに「はいの場合はCtl-aを入力してください」と答えてください:) – Barmar

0

あなたは

int repeat; 
+0

'cin >> repeat;'を実行する前に使われていないので、初期化する必要はありません。 – Barmar

+0

あなたは100%正しいです。私はいつもそうしていました;) – ApolloSoftware

+0

@Barmar、変更されました。私の姓はBarman btwです。 – ApolloSoftware

関連する問題