我是 C 新手,我正在尝试运行我书中的一个程序,该程序展示了我们如何处理结构数组。
#include<stdio.h>
#include<conio.h>
struct employee
{
int empno;
char name[30];
int basic;
int hra;
};
void main()
{
struct employee e[50];
int i, j, n;
int net[50];
float avg;
printf("Enter the number of employees: ");
scanf("%d", &n);
printf("Enter Emp. No. \tName:\tBasic\tHRA of each employee in the order.\n");
for(i=0; i<n; i++)
{
scanf("%d", &e[i].empno);
gets(e[i].name);
scanf("%d", &e[i].basic);
scanf("%d", &e[i].hra);
net[i]=e[i].basic + e[i].hra ;
avg = avg + net[i];
}
avg = avg/n;
printf("Emp. No \t Name-Netpay: ");
for(i=0; i<n; i++)
{
if(net[i]>avg)
{
printf("\t",e[i].empno);
printf("\t", e[i].name);
printf("\t", net[i]);
} } }
我还有其他模块,可以继续计算平均值并打印那些工资+小时高于平均水平的元素。但是,上面粘贴的代码无法按预期工作。
现在,如果我输入员 worker 数 - 假设为 1,它只允许我输入员工编号和姓名并退出循环。我期望它至少完成一个值为 1 的循环。
对此的任何建议都将受到高度赞赏,如果我在任何地方搞砸了,我深表歉意。谢谢。
最佳答案
在使用 gets 之前,您需要刷新输入中的行(顺便说一句,这已被弃用):
#include <stdio.h>
struct employee
{
int empno;
char name[30];
int basic;
int hra;
};
int main()
{
struct employee e[50];
int i, j, n;
int net[50];
float avg;
printf("Enter the number of employees: ");
scanf("%d", &n);
printf("Enter Emp. No. \tName:\tBasic\tHRA of each employee in the order.\n");
for(i=0; i<n; i++)
{
scanf("%d", &e[i].empno);
char c;
while ((c = getchar()) != EOF && c != '\n');
gets(e[i].name);
scanf("%d", &e[i].basic);
scanf("%d", &e[i].hra);
net[i]=e[i].basic + e[i].hra ;
avg = avg + net[i];
}
return 0;
}
这是因为 scanf
不会读取行尾 (\n
),但 gets
会读取并立即返回。 scanf
将读取名称。基本上,这是一团糟:)。
关于c - C 中的结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301209/