1.输入3个整数,按由大到小的顺序输出。用指针写程序
时间: 2024-02-13 14:03:12 浏览: 39
好的,这是一个简单的指针排序问题。可以使用冒泡排序来实现,以下是示例代码:
```c++
#include <iostream>
using namespace std;
void sort(int *a, int *b, int *c) {
if (*a < *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
if (*b < *c) {
int tmp = *b;
*b = *c;
*c = tmp;
}
if (*a < *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
}
int main() {
int a, b, c;
cout << "请输入三个整数:";
cin >> a >> b >> c;
sort(&a, &b, &c);
cout << "排序后的结果为:" << a << " " << b << " " << c << endl;
return 0;
}
```
这个程序中,sort函数用于排序,接受三个指针参数,指向输入的三个整数。主函数中,我们使用地址运算符&来获取变量a、b、c的地址,并将它们作为参数传递给sort函数。这样,sort函数就可以通过指针来修改变量a、b、c的值,达到排序的目的。
相关问题
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个整数,按照由小到大的顺序输出:
```c++
#include <iostream>
using namespace std;
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;
}
}
int main() {
int a, b, c;
cout << "请输入三个整数:" << endl;
cin >> a >> b >> c;
sort(&a, &b, &c);
cout << "排序后结果为:" << a << " " << b << " " << c << endl;
return 0;
}
```
在主函数中,首先提示用户输入三个整数,然后调用sort函数,将三个整数的地址传递给函数。在sort函数中,通过比较三个数的大小,交换它们的值,从而实现由小到大的排序。最后,在主函数中输出排序后的结果。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![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)