2012-07-17 112 views
0

我无法选择的功能从class OperateClass需要帮助从

它要求用户调用函数“你想加,减,乘或除我想:”(主)。无论我放什么,它都转到功能int add。我究竟做错了什么?

#include <iostream> 

using namespace std; 

int x = 1; 
int number; 
int total = 0; 
int amt = 1; 
int a; 
int b; 
int c; 
int d; 
string ans; 

class OperateClass{ 
    public: 
     int add(){ 
      while(x <= 2){ 
       cout << "Enter a number to use to add: " << endl; 
        cin >> a; 
       total = total + a; 
       x++; 
       amt++; 
      } 
     } 

     int subtract(){ 
      while(x <= 2){ 
       cout << "Enter a number to use to add: " << endl; 
        cin >> b; 
       total = total - b; 
       x++; 
       amt++; 
      } 
     } 

     int multiply(){ 
      while(x <= 2){ 
       cout << "Enter a number to use to add: " << endl; 
        cin >> c; 
       total = total * c; 
       x++; 
       amt++; 
      } 
     } 

     int divide(){ 
      while(x <= 2){ 
       cout << "Enter a number to use to add: " << endl; 
        cin >> d; 
       total = total/d; 
       x++; 
       amt++; 
      } 
     } 
}; 

int main() 
{ 

cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl; 
cin >> ans; 

if(ans == "add"){ 
OperateClass opOper; 
opOper.add(); 
    } 

else if (ans == "subtract"){ 
    OperateClass opOper; 
    opOper.subtract(); 
    } 

else if (ans == "multiply"){ 
    OperateClass opOper; 
    opOper.multiply(); 
    } 

else if(ans == "divide"){ 
    OperateClass opOper; 
    opOper.divide(); 

    } 

} 

另外,下面的功能是否足以打印?

void print(){ 
    cout << "Your total is: " << total << endl; Where should I call this? 

} 
+1

相同的文字你怎么知道的程序总是转到加()? 你的功能有相同的信息提示“输入一个数字用于添加:”。针对不同的功能有不同的信息。如“输入一个数字来划分”。 – 2012-07-17 02:53:15

+0

谢谢,我解决了这个问题。此外,我想知道为什么当我输入它提示的数字时,它没有运行void print()函数。 – Bucky763 2012-07-17 02:56:43

回答

2

你必须为所有方法"Enter a number to use to add: "

+0

哦,小错误。 – Bucky763 2012-07-17 02:54:36

+0

此外,我想知道为什么当我输入它提示的数字时,它没有运行void print()函数。 – Bucky763 2012-07-17 03:01:51

+1

你从来没有调用过print()。因此,如果您想在每次计算后打印总数,请在while循环后的每个函数中调用print()。 或在main()中,在所有if-else语句之后。 – 2012-07-17 03:02:01