C语言使用自定义函数sort(int a,int b)完成从小到大的排序功能 函数的参数:两个指针指向待排序的两个整数,函数执行完毕,使得a≤b 输入格式:4 3 2 输出格式:2 3 4
时间: 2023-11-22 16:54:18 浏览: 94
以下是使用自定义函数sort(int a,int b)完成从小到大的排序功能的C语言代码:
```c
#include<stdio.h>
void sort(int* a, int* b);
int main()
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
sort(&a, &b);
sort(&b, &c);
sort(&a, &b);
printf("%d %d %d", a, b, c);
return 0;
}
void sort(int* a, int* b)
{
if (*a > *b) {
int temp = *a;
*a = *b;
*b = temp;
}
}
```
在这个程序中,我们使用了一个自定义函数sort(int* a, int* b),其中a和b是指向待排序的两个整数的指针。在sort函数里,我们比较a和b的大小,如果a大于b,就交换它们的值,这样就可以使得a≤b。在主函数中,我们先读入三个整数a、b、c,然后分别调用sort函数来对它们进行排序。最后,我们输出排序后的结果。
需要注意的是,在调用sort函数时,我们需要传入指向a和b的指针,而不是直接传入a和b的值。这是因为我们要在sort函数中修改a和b的值,而指针可以让我们直接访问和修改变量的地址。
相关问题
用C语言编写,使用指针编写函数 ,使得输入四个整数,从小到大排序
好的,我明白了。以下是用C语言编写,使用指针编写函数,实现输入四个整数,从小到大排序的代码:
```c
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void sort(int *a, int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = i + 1; j < size; j++)
{
if (*(a+i) > *(a+j))
{
swap((a+i), (a+j));
}
}
}
}
int main()
{
int arr[4];
printf("Enter four integers: ");
scanf("%d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3]);
sort(arr, 4);
printf("Sorted array: %d %d %d %d", arr[0], arr[1], arr[2], arr[3]);
return 0;
}
```
这个程序的执行结果为:
```
Enter four integers: 4 1 3 2
Sorted array: 1 2 3 4
```
程序的主要思路是,定义一个 `swap` 函数,用于交换两个整数的值;然后定义一个 `sort` 函数,用于对指定数组进行排序;在 `main` 函数中,先输入四个整数,然后调用 `sort` 函数将它们从小到大排序,最后输出排序后的结果。
c语言输入三个数从小到大排序输出要求用函数和指针实现
下面是用函数和指针实现输入三个数从小到大排序输出的C语言代码:
```c
#include <stdio.h>
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;
printf("请输入三个数:");
scanf("%d%d%d", &a, &b, &c);
sort(&a, &b, &c);
printf("从小到大排序后的结果为:%d %d %d\n", a, b, c);
return 0;
}
```
首先在主函数中使用 `scanf` 函数输入三个数,然后调用 `sort` 函数进行排序。 `sort` 函数传入三个指针,利用指针访问和修改变量的值,实现对三个数的排序。最后在主函数中输出排序后的结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)