b) { temp = a;" />

四个整数顺序怎么编程

时间:2025-01-27 21:34:15 网络游戏

使用冒泡排序算法

```c

include

int main() {

int a, b, c, d, temp;

printf("请输入4个整数:");

scanf("%d %d %d %d", &a, &b, &c, &d);

// 冒泡排序

for (int i = 0; i < 4 - 1; i++) {

for (int j = 0; j < 4 - 1 - i; j++) {

if (a > b) {

temp = a;

a = b;

b = temp;

}

if (a > c) {

temp = a;

a = c;

c = temp;

}

if (a > d) {

temp = a;

a = d;

d = temp;

}

if (b > c) {

temp = b;

b = c;

c = temp;

}

if (b > d) {

temp = b;

b = d;

d = temp;

}

if (c > d) {

temp = c;

c = d;

d = temp;

}

}

}

printf("排序后的结果为:%d %d %d %d\n", a, b, c, d);

return 0;

}

```

使用选择排序算法

```c

include

int main() {

int a, b, c, d, temp;

printf("请输入4个整数:");

scanf("%d %d %d %d", &a, &b, &c, &d);

// 选择排序

for (int i = 0; i < 4 - 1; i++) {

int min_index = i;

for (int j = i + 1; j < 4; j++) {

if (a > b) {

temp = a;

a = b;

b = temp;

}

if (a > c) {

temp = a;

a = c;

c = temp;

}

if (a > d) {

temp = a;

a = d;

d = temp;

}

if (b > c) {

temp = b;

b = c;

c = temp;

}

if (b > d) {

temp = b;

b = d;

d = temp;

}

if (c > d) {

temp = c;

c = d;

d = temp;

}

}

// 将找到的最小值放到正确的位置

temp = a;

a = min_index;

min_index = a;

a = temp;

}

printf("排序后的结果为:%d %d %d %d\n", a, b, c, d);

return 0;

}

```

使用标准库函数`qsort`

```c

include

include

int compare(const void *a, const void *b) {

return (*(int*)a - *(int*)b);

}

int main() {

int a, b, c, d;

printf("请输入4个整数:");

scanf("%d %d %d %d", &a, &b, &c, &d);

int numbers[] = {a, b, c, d};

qsort(numbers, 4, sizeof(int), compare);

printf("排序后的结果为:%d %d %d %d\n", numbers, numbers, numbers, numbers);

return 0;

}

```

这些代码示例分别使用了冒泡排序、选择排序和标准库函数`qsort`来对四个整数进行排序,并按从小到大的顺序输出结果。你可以根据自己的需求选择合适的排序算法。