2017-03-03 76 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

你为什么不要求'y'或'n'而不是'1'或'0'? – Barmar

+0

也比较两条浮法这样'num_two == 0'是不是一个好主意 – Rama

+0

即使你解决重复问题,还有另外一个问题:你问的外循环的表达,所以它将继续给的答案相同表达。 – Barmar

回答

4

repeatchar,你应该测试对'1':否则

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

,你正在测试针对的十进制数值1,这在ASCII表相当于一个SOH或者“标题开始“字符,这是不可打印的。

此外,您需要将您的请求输入是循环的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

您可以更改

char repeat; 

int repeat; 
+0

没有必要初始化它,因为它没有在'cin >>重复之前使用';' – Barmar

+0

你100%正确。我一直有这样做的习惯;) – ApolloSoftware

+0

@Barmar,修改过。我的姓氏是巴特曼顺便说一句。 – ApolloSoftware