用c语言写 从键盘上输入10个数,前5个从小到大排序,后5个从大到小排序,用多个字符串的格式化输入输出
时间: 2023-06-16 13:06:32 浏览: 122
以下是用C语言实现从键盘上输入10个数,前5个从小到大排序,后5个从大到小排序,并使用多个字符串的格式化输入输出的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define NUM 10
int main() {
int nums[NUM];
int i, j, tmp;
// 从键盘输入10个数
printf("请输入10个数:\n");
for (i = 0; i < NUM; i++) {
scanf("%d", &nums[i]);
}
// 前5个从小到大排序
for (i = 0; i < 4; i++) {
for (j = 0; j < 4-i; j++) {
if (nums[j] > nums[j+1]) {
tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
// 后5个从大到小排序
for (i = 5; i < 9; i++) {
for (j = 5; j < 9-(i-5); j++) {
if (nums[j] < nums[j+1]) {
tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
// 使用多个字符串的格式化输出
char str1[50] = "前五个从小到大排序:";
char str2[50] = "后五个从大到小排序:";
char str3[50] = "所有数从小到大排序:";
char buf[10];
// 输出前五个排序结果
strcat(str1, "\n");
for (i = 0; i < 5; i++) {
sprintf(buf, "%d ", nums[i]);
strcat(str1, buf);
}
// 输出后五个排序结果
strcat(str2, "\n");
for (i = 5; i < NUM; i++) {
sprintf(buf, "%d ", nums[i]);
strcat(str2, buf);
}
// 对所有数进行从小到大排序
for (i = 0; i < NUM-1; i++) {
for (j = 0; j < NUM-1-i; j++) {
if (nums[j] > nums[j+1]) {
tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
// 输出所有数排序结果
strcat(str3, "\n");
for (i = 0; i < NUM; i++) {
sprintf(buf, "%d ", nums[i]);
strcat(str3, buf);
}
// 输出结果
printf("%s\n%s\n%s\n", str1, str2, str3);
return 0;
}
```
运行示例:
```
请输入10个数:
10 9 8 7 6 5 4 3 2 1
前五个从小到大排序:
1 2 3 4 5
后五个从大到小排序:
10 9 8 7 6
所有数从小到大排序:
1 2 3 4 5 6 7 8 9 10
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![c](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)