c+++编写重载函数max
时间: 2023-06-11 20:08:50 浏览: 57
可以使用函数重载来实现不同类型数据的比较,下面是一个示例代码:
```c
#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
float max(float a, float b) {
return (a > b) ? a : b;
}
double max(double a, double b) {
return (a > b) ? a : b;
}
int main() {
int a = 10, b = 20;
float c = 3.14, d = 6.28;
double e = 1.2345, f = 6.7890;
printf("max of %d and %d is %d\n", a, b, max(a, b));
printf("max of %.2f and %.2f is %.2f\n", c, d, max(c, d));
printf("max of %.4lf and %.4lf is %.4lf\n", e, f, max(e, f));
return 0;
}
```
输出结果如下:
```
max of 10 and 20 is 20
max of 3.14 and 6.28 is 6.28
max of 1.2345 and 6.7890 is 6.7890
```
在上面的代码中,我们定义了三个不同版本的max函数,分别用于比较int、float和double类型的数据。在main函数中,我们分别调用了这三个函数,并打印出了比较结果。