c++ 编写程序创建Number类,它有两个整形函数成员x和y。它应包含成员函数以读取数据,对两个函数进行加,减,乘,除运算,并显示结果
时间: 2023-06-01 10:05:46 浏览: 28
好的,我可以帮你回答这个问题。以下是一个示例代码:
```
#include <iostream>
using namespace std;
class Number {
private:
int x, y;
public:
void input() {
cout << "Enter the first number: ";
cin >> x;
cout << "Enter the second number: ";
cin >> y;
}
void add() {
cout << "Addition result: " << x + y << endl;
}
void subtract() {
cout << "Subtraction result: " << x - y << endl;
}
void multiply() {
cout << "Multiplication result: " << x * y << endl;
}
void divide() {
if (y == 0) {
cout << "Cannot divide by zero." << endl;
} else {
cout << "Division result: " << x / y << endl;
}
}
};
int main() {
Number num;
num.input();
num.add();
num.subtract();
num.multiply();
num.divide();
return 0;
}
```
以上代码创建了一个名为 `Number` 的类,其包括两个私有成员变量 `x` 和 `y` 以及五个公有成员函数 `input`、`add`、`subtract`、`multiply` 和 `divide`。`input` 函数用于读取两个整数,而剩余的四个函数分别对这两个数进行加、减、乘、除运算,并输出结果。
你可以在 `main` 函数中创建一个 `Number` 对象,并调用其成员函数以实现所需的功能。希望这可以帮到你!