c语言编写函数求两个数
时间: 2023-12-03 22:47:03 浏览: 65
C语言实现求两个数的加减乘除
4星 · 用户满意度95%
你的问题不太清楚,是要求两个数的和、差、积还是商?下面我就分别给出这些函数的示例代码。
1. 求两个数的和
```c
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int num1 = 10, num2 = 20;
int sum = add(num1, num2);
printf("The sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
```
2. 求两个数的差
```c
#include <stdio.h>
int sub(int a, int b) {
return a - b;
}
int main() {
int num1 = 20, num2 = 10;
int diff = sub(num1, num2);
printf("The difference between %d and %d is %d\n", num1, num2, diff);
return 0;
}
```
3. 求两个数的积
```c
#include <stdio.h>
int mul(int a, int b) {
return a * b;
}
int main() {
int num1 = 5, num2 = 8;
int product = mul(num1, num2);
printf("The product of %d and %d is %d\n", num1, num2, product);
return 0;
}
```
4. 求两个数的商
```c
#include <stdio.h>
float div(float a, float b) {
return a / b;
}
int main() {
float num1 = 10.0, num2 = 3.0;
float quotient = div(num1, num2);
printf("The quotient of %f and %f is %f\n", num1, num2, quotient);
return 0;
}
```
注意,对于除法运算,我们需要使用 `float` 类型而不是 `int` 类型,否则结果可能不准确。
阅读全文