利用指针编写一函数,输入3个整数,按由大到小的顺序将它们输出。
时间: 2023-04-19 13:03:59 浏览: 110
以下是利用指针编写的函数,实现输入3个整数,按由大到小的顺序输出:
```c
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;
}
printf("%d %d %d\n", *a, *b, *c);
}
```
函数接受3个整数的指针作为参数,通过比较大小,将它们按由大到小的顺序排序,并输出。
相关问题
用指针方法编写一个程序,输入3个整数,将它们按由小到大的顺序输出
以下是用指针方法编写的程序,输入3个整数,将它们按由小到大的顺序输出:
```c
#include <stdio.h>
void sort(int *a, int *b, int *c);
int main()
{
int a, b, c;
printf("请输入3个整数:\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;
}
}
```
程序中定义了一个 `sort` 函数,它接收三个整数指针作为参数,用于将这三个整数按由小到大的顺序排序。在 `main` 函数中,先输入三个整数,然后调用 `sort` 函数进行排序,最后按照顺序输出这三个整数。
用指针方法编写程序,输入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函数中,通过比较三个数的大小,交换它们的值,从而实现由小到大的排序。最后,在主函数中输出排序后的结果。