调用求和或获取乘积的函数不正确

The function being called to sum or get product is incorrect

本文关键字:函数 不正确 求和 获取 调用      更新时间:2023-10-16

当我运行这个函数时,总和或乘积是严重错误的。我输入了 2 和 3,得到了负一百万。产品也是如此。在我询问他们想要进行哪种计算以使其更自然之后,我将添加另一个 cout 语句。

#include <iostream>
#include <math.h>
#include <string>
using namespace std;
class basicCalculator {
public:
int add(int x,int y) {
    return add1 + add2;
}
int multiply(int x,int y) {
    return multiply1*multiply2;
}
private:
int add1;
int add2;
int multiply1;
int multiply2;
};
int main() {
cout << "What mathematical action do you want?" << endl;
cout << "Press '1' to add two numbers, '2' to multiply two numbers" << endl;
int method;
cin >> method;
int value1;
cin >> value1;
int value2;
cin >> value2;
basicCalculator bc;
switch (method) {
case 1:
    cout << "The sum is " << bc.add(value1, value2) << endl;
    break;
case 2:
    cout << "The product is " << bc.multiply(value1, value2) << endl;
}

}

addmultiply方法中,您使用的是(非初始(成员变量,而不是实际的参数。

尝试:

int add(int x, int y) { return x + y; }

建议:addmultiply根本不需要对象状态,它们可能是静态的,我看不出您声明的所有成员变量有任何理由。

Freddy,在你的函数中,你必须使用命名参数进行计算。所以,不是

int add(int x,int y) {
    return add1 + add2;
}

而是

int add(int x,int y) {
    return x + y;
}

乘法也有同样的问题。