#include <stdio.h>
#include <stdlib.h>
//第四题,冒泡排序法
int main()
{
double salary[500];
double temp_num;
int i,j;
FILE *fp1,*fp2;
fp1 = fopen("salary.txt", "r");
fp2 = fopen("ordered_salary.txt", "w");
for (i = 0; i < 500; i++)
{
fscanf(fp1, "%lf",&temp_num);
salary[i] = temp_num*1.2;
}
for (i = 0; i < 499; i++)
for (j = 0; j < 499 - i; j++)
{
if (salary[j]>salary[j + 1])
{
temp_num = salary[j];
salary[j] = salary[j + 1];
salary[j + 1] = temp_num;
}
}
for (i = 0; i < 500; i++)
fprintf(fp2, "%.2lf\n", salary[i]);
fclose(fp1);
fclose(fp2);
return 0;
}
改进了文件的操作,增加了异常判断
#include <stdio.h>
#include <stdlib.h>
//第四题,冒泡排序法
int main()
{
double salary[500];
double temp_num;
int i,j;
FILE *fp1,*fp2;
fp1 = fopen("salary.txt", "r");
fp2 = fopen("ordered_salary.txt", "w");
if (fp1 == NULL)
{
printf("打开文件失败\n");
exit(1);//exit(1)表示异常退出,exit(0)为正常退出
}
if (fp2 == NULL)
{
printf("写入文件失败\n");
exit(1);
}
for (i = 0; i < 500; i++)
{
if ((fscanf(fp1, "%lf", &temp_num)) != EOF)//判断读取到边界,文件中数据不足500的情况
salary[i] = temp_num*1.2;
else
break;
}
for (i = 0; i < 499; i++)
for (j = 0; j < 499 - i; j++)
{
if (salary[j]>salary[j + 1])
{
temp_num = salary[j];
salary[j] = salary[j + 1];
salary[j + 1] = temp_num;
}
}
for (i = 0; i < 500; i++)
fprintf(fp2, "%.2lf\n", salary[i]);
fclose(fp1);
fclose(fp2);
return 0;
}