调用函数fun(),其功能是用选择法对5个整数按降序进行排序,结果写入文件result5.txt中。其中main函数已知,请编写fun函数与myprintf函数,其中myprintf函数为写入文件功能
时间: 2024-05-08 19:14:41 浏览: 17
的函数。注意,文件名为result5.txt,文件路径为当前路径。以下是代码:
```python
#include <stdio.h>
// 选择排序函数,按降序排列
void select_sort(int arr[], int length) {
int i, j, min_index, temp;
for (i = 0; i < length - 1; i++) {
min_index = i;
for (j = i + 1; j < length; j++) {
if (arr[j] > arr[min_index]) {
min_index = j;
}
}
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
// 写入文件函数
void myprintf(char *filename, int arr[], int length) {
FILE *fp;
fp = fopen(filename, "w"); // 打开文件
if (fp == NULL) { // 判断文件是否打开成功
printf("Cannot open file.\n");
return;
}
int i;
for (i = 0; i < length; i++) {
fprintf(fp, "%d ", arr[i]); // 写入文件
}
fclose(fp); // 关闭文件
}
// 用选择法对5个整数降序排序,结果写入文件result5.txt中
void fun() {
int arr[5] = {3, 1, 4, 2, 5}; // 五个整数
int length = sizeof(arr) / sizeof(int); // 整数个数
select_sort(arr, length); // 选择排序,按降序排列
myprintf("result5.txt", arr, length); // 写入文件
}
// main函数
int main() {
fun(); // 调用函数fun
return 0;
}
```
运行结果为:result5.txt文件中写入5个整数:5 4 3 2 1。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)