2014-01-26 103 views
0

我想在C++中做一个简单的计算器。下面是部分代码:程序不会退出执行循环

#include <iostream> 
#include <string> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    int math; 
    int a1; 
    int a2 = 0; 
    int a3 = 1; 
    int answer; 
    int amount = 0; 
    int achecker = 1; 

    cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, " 
      "type '3' to multiply, type '4' to divide, and type '5' to exit." 
     << endl; 
    cin >> math; 

    while (math = 1) 
    { 
     cout << "Input how many numbers you wish to add:" << endl; 
     cin >> amount; 
     achecker = amount; 
     do 
     { 
      cout << "Input the number you wish to add:" << endl; 
      cin >> a1; 
      answer = a1 + a2; 
      a2 = a1; 
      achecker = achecker - achecker + 1; 
     } while (achecker < amount); 
     cout << answer; 
    } 

我遇到的问题是,当程序进入了do-while循环,它永远不会出来,它只是不断要求用户输入一个数。我经历了这几次,我不知道问题是什么。有人可以帮忙吗?

+5

[调高你的警告级别(http://coliru.stacked-crooked.com/a/fbe8856d94bfe1c6) – chris

+0

这个表达式'achecker = achecker - achecker + 1;'将'1'赋予'achecker',而不管它以前的值如何(提示:'achecker - achecker'为零;零加1就是一个)。 – dasblinkenlight

+0

..并缩进代码 –

回答

0

首先,你应该写,而(数学== 1) sicnce 数学= 1是赋值运算符不检查操作。

其次,而不是,使用如果,因为你想要做加法计算只有一次,把它在循环,可以使一个无限循环。

第三,在做 - while循环,病情应该是,而(achecker> = 0),因为你的病情总是会给一个真正的value.So,其实,没有必要achecker的,只需在每次循环运行时将递减量减1,并将条件保留为,同时(金额> = 0)

一,多改进我想建议,但并不是必需的 - 声明答案INT答案= 0;。对于每次循环运行,接受a1中的新值然后进行添加,编写answer = answer + a1。这应该是你的目的。

因此,根据我应该是编辑的代码 -

#include <iostream> 
#include <string> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    int math; 
    int a1; 
    int a3 = 1; 
    int answer = 0; 
    int amount = 0; 
    int achecker = 1; 

    cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, type '3' to  multiply, type '4' to divide, and type '5' to exit." << endl; 
    cin >> math; 

    if(math == 1){ 
    cout << "Input how many numbers you wish to add:" << endl; 
    cin >> amount; 
    do{ 
    cout << "Input the number you wish to add:" << endl; 
    cin >> a1; 
    answer = answer + a1; 
    amount = amount - 1; 
    }while(amount>=0); 
    cout << answer; 
    } 
1

您在while循环中检查了错误的条件。

match=1是赋值操作,而不是相等性检查,这是你正在尝试做的。该分配将始终返回1(真),因此您有一个无限循环。

取代match=1match==1为您的代码工作

+0

谢谢,但它仍然通过do循环循环。 – TheBlackSword

+0

用于调试的打印量值。我会帮你的 –

1

achecker = achecker - achecker + 1;总是等于1。所以我认为你必须在该行的错误。