交换指针的方式输入三个数的大小关系
时间: 2024-02-06 09:09:54 浏览: 38
可以使用指针交换的方式来输入三个数的大小关系,具体实现如下:
```c++
#include <iostream>
using namespace std;
void swap(int* p1, int* p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main() {
int a, b, c;
int* p1 = &a;
int* p2 = &b;
int* p3 = &c;
cout << "请输入三个整数,以空格分隔:" << endl;
cin >> a >> b >> c;
if (*p1 > *p2) {
swap(p1, p2);
}
if (*p1 > *p3) {
swap(p1, p3);
}
if (*p2 > *p3) {
swap(p2, p3);
}
cout << "从小到大的顺序是:" << *p1 << " " << *p2 << " " << *p3 << endl;
return 0;
}
```
在这个程序中,我们首先定义了三个指针 p1、p2、p3 分别指向三个变量 a、b、c。然后通过 cin 输入三个整数。接下来,我们使用指针交换的方式对三个数进行排序,最终输出从小到大的顺序。
相关问题
以间接访问和交换指针的方式输入三个数的大小关系与三个数的和
可以使用以下代码实现:
```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`函数中,我们将三个整数变量的地址传递给这三个函数,实现了指针的间接访问和交换。
用指针比较三个数大小
以下是用指针比较三个数大小的C语言代码实现,其中使用了指针作为形参,通过指针间接访问变量的值,实现了三个数的比较和交换,最终输出由小到大的结果:
```c
#include <stdio.h>
//定义数据交换函数,指针作为形参
void swap(int *s1, int *s2){
int t;//中间变量,临时存储
t = *s1;
*s1 = *s2;
*s2 = t;
}
int main(){
int a, b, c;//定义三个数据
int *p1, *p2, *p3;//定义3个 int型指针
printf("输入 a, b ,c :");//信息提示
scanf("%d %d %d", &a, &b, &c);//读取数据
p1 = &a;
p2 = &b;
p3 = &c;//取地址初始化指针
//比较大小
if(*p1 > *p2){
swap(p1, p2);
}
if(*p1 > *p3){
swap(p1, p3);
}
if(*p2 > *p3){
swap(p2, p3);
}
printf("由小到大为:%d %d %d\n", a, b, c);//输出结果
return 0;
}
```