0
using namespace std;

//a class that will handle all the calculations requested by user

class MathOperations{
  public:
    void Message();
    int setSum(int,int);
    int setSuB(int,int);
    int setMul(int,int);
    float setDiv(float,float *);
    int setSqrt(int);
};

//Implementation:

void MathOperations:: Message(){
    cout<< " Welcome. This program simulates a calculator "<<endl;
}
// implementing the setters methods.
int MathOperations::setSum(int a, int b){

    int total;
    total = a + b;
    return total;
} 
int MathOperations:: setSuB(int a, int b){
    int total;
    total = a - b;
    return total;
}
int MathOperations:: setMul(int a, int b){
    int total;
    total = a * b;
    return total;
}

float MathOperations:: setDiv(float a, float *b){
    float result;
    if(b ==0){
        cout << "Using the Default Value of 1 because you can't devide by 0"<<endl;
    }
    else
        result = (a / *b);
    return result;
}

int MathOperations::setSqrt(int Square){
    int total;
    total = sqrt(Square);
    return total;
}

int main(int argc, const char * argv[])
{
    //creating instances of class MathOperations
    MathOperations add, sub, mul, div, sqrt;
    ///creating variable to hold user input

    int fnum;
    float snum;
    char opt= '0';

    //propt user for values
    cout << " Enter a Number"<<endl;
    cin >> fnum;

    cout << " Enter a second number " <<endl;
    cin >> snum;

    float total = div.setDiv(fnum, &snum);

    cout << total <<endl;


    cout << " What would you like to do '+','-','*','/' ?"<<endl;
    cin >> opt;

    switch (opt) {
      case '+' :
        {
            int total = add.setSum(fnum, snum);
            cout << " The Total Sum of both numbers is " << total <<endl;
        }
        break;
      case '-' :
        {
            int total = sub.setSuB(fnum, snum);
            cout << " The Subtraction of both Numbers is " << total << endl;
        }
        break;
      case '*' :
        {
            int total = mul.setMul(fnum, snum);
            cout << " The Multiplication of both Numbers is " << total << endl;
        }
        break;
      case '/' :
        {
            int total = div.setDiv(fnum, &snum);
            cout << " The Division of both Numbers is " << total <<endl;
        }
      default:
        cout << " Not a valid Option"<<endl;
    }

}

该部门工作不正常。我在这里做错了什么?我正在尝试创建一个包含数学运算的类。我是一个初学者,想在这里做一些练习。你能具体告诉我我做错了什么吗?

4

3 回答 3

0

The second parameter of the function div should not be a pointer. At least I don't see any reason for it being a pointer.

So just remove the * and & from the variable snum.

于 2012-07-20T16:24:19.687 回答
0

您没有在 setDiv 函数中保护自己免于被 0 除,因为您没有首先将第二个浮点数与 0 进行比较。您只是将其地址与 NULL 进行比较。

并且错误消息没有意义:程序不会以任何方式“使用 1”。

如果指针恰好为 NULL,那么您将返回一个未初始化的值。

于 2012-07-20T16:30:06.167 回答
0

当您说您使用 1 而不是 0 时,您永远不会将 b 的值更改为 1。

于 2012-07-20T16:31:01.940 回答