c++定义五个函数加减乘除取余
时间: 2024-11-13 13:25:27 浏览: 17
在 C++ 中,你可以定义一组包含加、减、乘、除和取余运算的函数,通常这些操作都是基本数学运算,适用于整数和浮点数。这里是一个简单的示例:
```cpp
#include <iostream>
// 加法函数
int add(int a, int b) {
return a + b;
}
// 减法函数
int subtract(int a, int b) {
return a - b;
}
// 乘法函数
int multiply(int a, int b) {
return a * b;
}
// 除法函数(注意,整数除法会向下取整)
int divide(int a, int b) {
if (b != 0)
return a / b;
else
throw std::invalid_argument("Division by zero is not allowed.");
}
// 取余运算符(求模)
int remainder(int a, int b) {
if (b != 0)
return a % b;
else
throw std::invalid_argument("Modulus by zero is not valid.");
}
// 测试这些函数
int main() {
int num1 = 5, num2 = 2;
std::cout << "Addition: " << add(num1, num2) << std::endl;
std::cout << "Subtraction: " << subtract(num1, num2) << std::endl;
std::cout << "Multiplication: " << multiply(num1, num2) << std::endl;
std::cout << "Division: " << divide(num1, num2) << std::endl;
std::cout << "Remainder: " << remainder(num1, num2) << std::endl;
return 0;
}
```
阅读全文