C++编写的简单示例,实现一个计算器,支持加减乘除四则运算
1.创建一个calculator.h头文件,用于声明Calculator类,代码如下:
#ifndef CALCULATOR_H
#define CALCULATOR_H
class Calculator {
public:
Calculator();
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
};
#endif
在Calculator类中,我们声明了构造函数、加法、减法、乘法和除法的成员函数。
2.创建一个calculator.cpp源文件,实现Calculator类的成员函数,代码如下:
#include "calculator.h"
Calculator::Calculator() {
// 构造函数
}
double Calculator::add(double a, double b) {
return a + b;
}
double Calculator::subtract(double a, double b) {
return a - b;
}
double Calculator::multiply(double a, double b) {
return a * b;
}
double Calculator::divide(double a, double b) {
if (b == 0) {
return 0; // 除数为0,返回0
} else {
return a / b;
}
}
在add()函数中,我们计算a和b的和。在subtract()函数中,我们计算a和b的差。在multiply()函数中,我们计算a和b的积。在divide()函数中,我们首先判断除数是否为0,如果为0则返回0,否则计算a和b的商。
3.创建一个main.cpp源文件,实现程序的主要逻辑,代码如下:
#include <iostream>
#include "calculator.h"
int main() {
Calculator calc;
// 加法
std::cout << "2 + 3 = " << calc.add(2, 3) << std::endl;
// 减法
std::cout << "5 - 1 = " << calc.subtract(5, 1) << std::endl;
// 乘法
std::cout << "4 * 6 = " << calc.multiply(4, 6) << std::endl;
// 除法
std::cout << "8 / 2 = " << calc.divide(8, 2) << std::endl;
std::cout << "8 / 0 = " << calc.divide(8, 0) << std::endl;
return 0;
}
在main()函数中,我们创建一个Calculator对象,然后分别进行加法、减法、乘法和除法的计算,并输出结果。
上述代码只是一个简单的C++计算器示例,实际开发中需要根据具体需求进行相应的调整和开发。