计算机科学-第6周 文件 题目及参考解答

《计算机科学》课程主页在:http://blog.csdn.net/sxhelijian/article/details/13705597


题目:文件salary1.txt是某单位100名员工的工号、基本工资和绩效工资。编程序
(1)从文件中读取数据,求出总工资,并在屏幕上显示信息;
(2)将完整的工资单保存到文件salary2.txt中。
(3)将总工资超过5000元的员工的工号保存到文件rich.txt中。
(4)在屏幕上显示工资最高的员工的工资信息
提示:
(1)定义一个结构体数组保存从文件中读入的信息
(2)采用渐增式策略,逐步完成上述4项功能。


参考解答:

#include<stdio.h>
struct Stuff
{
    int num;
    float pay;
    float PRP;    //Performance Related Pay;
    float total;
};

int main()
{
    FILE *fp;
    fp = fopen("salary1.txt", "r");
    if (fp == NULL)
    {
        printf("cannot open file salary.txt.\n");
        return 0;
    }
    struct Stuff s[100];
    int i;
    //(1)从文件中读取数据,求总工资,并在屏幕上显示;
    for (i=0; i<100; i++)
    {
        fscanf(fp,"%d %f %f",&s[i].num,&s[i].pay,&s[i].PRP);
        s[i].total=s[i].pay+s[i].PRP;
        printf("%d %.2f %.2f %.2f\n", s[i].num,s[i].pay,s[i].PRP,s[i].total);
    }
    fclose(fp);
    //(2)将完整的工资单保存到文件salary2.txt中。
    FILE *fp2 = fopen("salary2.txt", "w");
    if (fp == NULL)
    {
        printf("cannot open file salary2.txt.\n");
        return 0;
    }
    for (i=0; i<100; i++)
    {
        fprintf(fp2,"%d %.2f %.2f %.2f\n", s[i].num,s[i].pay,s[i].PRP,s[i].total);
    }
    fclose(fp2);
//(3)将总工资超过5000元的员工的工号保存到文件rich.txt中。
    FILE *fp3 = fopen("rich.txt", "w");
    if (fp == NULL)
    {
        printf("cannot open file rich.txt.\n");
        return 0;
    }
    for (i=0; i<100; i++)
    {
        if(s[i].total>=5000)
            fprintf(fp3,"%d\n", s[i].num);
    }
    fclose(fp3);
//(4)在屏幕上显示工资最高的员工的工资信息
    float max = s[0].total;
    int h=0;
    for (i=1; i<100; i++)
    {
        if(max<s[i].total)
        {
            max=s[i].total;
            h=i;
        }
    }
    printf("收入最高的是: ");
    printf("%d %.2f %.2f %.2f\n", s[h].num,s[h].pay,s[h].PRP,s[h].total);
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值