用指针法,应用函数,输入3个整数,按由小到大的顺序存放。
时间: 2024-03-01 14:51:26 浏览: 28
好的,可以使用指针法和函数来实现这个功能,下面是示例代码:
```c
#include <stdio.h>
void sort(int *a, int *b, int *c) {
int tmp;
if (*a > *b) {
tmp = *a;
*a = *b;
*b = tmp;
}
if (*a > *c) {
tmp = *a;
*a = *c;
*c = tmp;
}
if (*b > *c) {
tmp = *b;
*b = *c;
*c = tmp;
}
}
int main() {
int a, b, c;
printf("请输入三个整数:\n");
scanf("%d %d %d", &a, &b, &c);
sort(&a, &b, &c);
printf("由小到大的顺序为:%d %d %d\n", a, b, c);
return 0;
}
```
代码中的 `sort` 函数接收三个指向整型变量的指针,使用冒泡排序的思想将三个整数按由小到大的顺序排列。在 `main` 函数中,通过 `scanf` 函数读取三个整数,然后将它们的地址传递给 `sort` 函数进行排序。最后输出排好序的三个整数。
相关问题
c语言输入三个整数按由小到大的顺序输出用指针
以下是一个用指针实现的C语言程序,用于输入三个整数并按照由小到大的顺序输出:
```c
#include<stdio.h>
void sort(int *q1, int *q2, int *q3);
void swap(int *p4, int *p5);
int main() {
int a, b, c;
int *p1, *p2, *p3;
scanf("%d%d%d", &a, &b, &c);
p1 = &a;
p2 = &b;
p3 = &c;
sort(p1, p2, p3);
printf("%d %d %d", a, b, c);
return 0;
}
void sort(int *q1, int *q2, int *q3) {
void swap(int *p4, int *p5);
if (*q1 < *q2)
swap(q1, q2);
if (*q1 < *q3)
swap(q1, q3);
if (*q2 < *q3)
swap(q2, q3);
}
void swap(int *p4, int *p5) {
int t;
t = *p4;
*p4 = *p5;
*p5 = t;
}
```
这个程序首先定义了两个函数`sort`和`swap`,分别用于排序和交换两个整数的值。然后在`main`函数中,通过指针将输入的三个整数与变量`a`、`b`、`c`关联起来。接下来,调用`sort`函数对这三个整数进行排序。最后,使用`printf`函数按照由小到大的顺序输出这三个整数。
用指针方法实现输入3个整数按由小到大的顺序输出
以下是用指针方法实现输入3个整数按由小到大的顺序输出的代码:
```
#include <stdio.h>
void sort(int *a, int *b, int *c);
int main() {
int a, b, c;
printf("请输入三个整数:\n");
scanf("%d%d%d", &a, &b, &c);
sort(&a, &b, &c);
printf("按由小到大的顺序输出为:%d %d %d\n", a, b, c);
return ;
}
void sort(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;
}
}
```
解释一下代码:
1. 首先在主函数中输入三个整数a、b、c,并调用sort函数进行排序。
2. sort函数中使用指针方法,将a、b、c的地址传递给函数,通过比较大小,将它们按由小到大的顺序排列。
3. 最后在主函数中输出排序后的结果。
希望能对你有所帮助!
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)