以间接访问和交换指针的方式输入三个数的大小关系与三个数的和
时间: 2024-02-06 10:09:53 浏览: 22
可以使用以下代码实现:
```c++
#include <iostream>
using namespace std;
void input(int *a, int *b, int *c) {
cout << "请输入三个整数:" << endl;
cin >> *a >> *b >> *c;
}
void compare(int *a, int *b, int *c) {
int temp;
if (*a < *b) {
temp = *a;
*a = *b;
*b = temp;
}
if (*a < *c) {
temp = *a;
*a = *c;
*c = temp;
}
if (*b < *c) {
temp = *b;
*b = *c;
*c = temp;
}
cout << "最大的数为:" << *a << endl;
cout << "最小的数为:" << *c << endl;
}
void sum(int *a, int *b, int *c) {
int s = *a + *b + *c;
cout << "三个数的和为:" << s << endl;
}
int main() {
int a, b, c;
input(&a, &b, &c);
compare(&a, &b, &c);
sum(&a, &b, &c);
return 0;
}
```
首先,`input`函数通过指针间接访问三个整数变量,接收用户输入的三个整数。然后,`compare`函数使用指针交换的方式比较三个整数的大小关系,让最大的数存储在变量`a`中,最小的数存储在变量`c`中,并输出最大值和最小值。最后,`sum`函数通过指针间接访问三个整数变量,计算它们的和并输出。在`main`函数中,我们将三个整数变量的地址传递给这三个函数,实现了指针的间接访问和交换。