【问题标题】:structures in c to store details of employees and print those who get more than 10000c 中的结构来存储员工的详细信息并打印获得超过 10000 的人员
【发布时间】:2015-10-16 20:32:26
【问题描述】:

我应该获取 4 名员工的详细信息并打印工资超过 10000 的人员的详细信息。我不应该更改程序的结构。当我编译这段代码时,我没有收到任何错误,但输出只是

0  0.00
0  0.00
0  0.00

我找不到错误的地方。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct employee
{ int id;
    char name[10];
    float sal;
} EMP;

void init_emp_rec(EMP out_rec[]);
void print_emp_rec(EMP out_rec[]);

void emp_recordMain(EMP emp_rec[], EMP out_rec[])
{
    for(int i=0; i<3; i++)
    {
        if(emp_rec[i].sal>10000)
        {
            out_rec[i].id=emp_rec[i].id;
            strcpy(out_rec[i].name,emp_rec[i].name);
            out_rec[i].sal=emp_rec[i].sal;
        }
    }        
}

void init_emp_rec(EMP out_rec[])
{
    memset(out_rec, 0, sizeof(EMP)*4);
}

void print_emp_rec(EMP out_rec[])
{   
    for(int i=0; i<3; i++)    
    {
        printf("%d %s %.2f", out_rec[i].id, out_rec[i].name, out_rec[i].sal);
        if(i!=2){printf("\n");}
    }
}

main(int argc, const char** argv)
{
    int i;
    EMP emp_rec[4];
    EMP out_rec[4];
    init_emp_rec(out_rec);
    init_emp_rec(emp_rec);
    for(int i=0; i<4; i++)
    {
        scanf("%d",&emp_rec[i].id);
        scanf("%s",&emp_rec[i].name);
        scanf("%0.2f",&emp_rec[i].sal);
    }    
    emp_recordMain(emp_rec, out_rec);
    print_emp_rec(out_rec);
}

【问题讨论】:

  • 您在每个函数中都有错误的i 循环计数器,请将3 更改为4。还将scanf 格式从"%0.2f" 更改为"%f"。同样对于"%s" 格式,删除&amp;emp_rec[i].name 前面的&amp;
  • Related: 如果 out_rec 应该只包含工资超过 10000 的记录的副本,我建议您在制作副本时使用 out_rec 的单独索引(可以通过结构来完成作业,顺便说一句)。否则,您的 out_rec 数组中将有“洞”用于匹配不符合您条件的 emp_rec 索引。

标签: c structure


【解决方案1】:

看来您需要稍微修改一下代码:

scanf("%f",&emp_rec[i].sal);

"%0.2f" 会将 20000 视为 0。

【讨论】:

  • 对于"%0.2f",GCC 特别警告零宽度,并认为. 是一个未知的转换类型字符......所以它甚至不会扫描浮点数。
【解决方案2】:

rec[i].name 已经是字符串的地址,所以你应该使用:

  scanf("%s",emp_rec[i].name);

此外,您在读取浮点数时不应使用格式说明符(“0.2”):

  scanf("%f",&emp_rec[i].sal);

我觉得还有其他问题需要解决,但我不想危及您的锻炼 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多