c++用值调用,引用调用和全局变量来求三个整数的最大值,最小值,平均值
时间: 2023-05-22 12:05:47 浏览: 115
最大值和最小值可以使用值调用和引用调用来求解,平均值可以使用全局变量来求解。以下是示例代码:
值调用:
```
#include <stdio.h>
int max(int a, int b, int c) {
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
int min(int a, int b, int c) {
int min = a;
if (b < min) {
min = b;
}
if (c < min) {
min = c;
}
return min;
}
int main() {
int a = 10, b = 20, c = 30;
printf("Max value: %d\n", max(a, b, c));
printf("Min value: %d\n", min(a, b, c));
return 0;
}
```
引用调用:
```
#include <stdio.h>
void max_min(int a, int b, int c, int *max, int *min) {
*max = a;
*min = a;
if (b > *max) {
*max = b;
}
if (c > *max) {
*max = c;
}
if (b < *min) {
*min = b;
}
if (c < *min) {
*min = c;
}
}
int main() {
int a = 10, b = 20, c = 30;
int max_val, min_val;
max_min(a, b, c, &max_val, &min_val);
printf("Max value: %d\n", max_val);
printf("Min value: %d\n", min_val);
return 0;
}
```
全局变量:
```
#include <stdio.h>
int sum = 0, count = 0; // 全局变量
void addValue(int val) {
sum += val;
count++;
}
double getAverage(){
if (count == 0) {
return 0;
}
return (double) sum / count;
}
int main() {
addValue(10);
addValue(20);
addValue(30);
printf("Average value: %.2f\n", getAverage());
return 0;
}
```
输出:
```
Max value: 30
Min value: 10
Average value: 20.00
```
阅读全文