帮忙看个c语言小问题,先谢谢了

来源:百度知道 编辑:UC知道 时间:2024/05/22 15:22:08
我测试了,总是答案不对,好象是后面的数字接受成为字符串了
比如我输入的是
zhang,danweia,100,11
wanga,danweib,200,22
lixia,danweic,300,33
zhaoq,danweid,400,44
结果输出是:
zhang,danweia,100,11 danweia,100,11 0 0 0
wanga,danweib,200,22 danweib,200,22 0 0 0
lixia,danweic,300,33 danweic,300,33 0 0 0
zhaoq,danweid,400,44 danweid,400,44 0 0 0
0 0 0

而且不知道为什么后面还多出来一行3个0?

#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct employer)
#define SIZE 4

struct employer
{
char name[5];
char department[20];
float basepay,allowance,total;
struct employer * next;
}emp[SIZE];

void save()
{
FILE *fp;
int i;
if( (fp=fopen("paybase","wb"))==NULL )
{
printf("cannot open this file!!!!\n");
return;
}<

这样的程序运行也不出错,你的电脑真是太强了!

首先,你在employer中定义:float basepay,allowance,total;
而你输入的时候用的是%d!!,输出的时候也是用%d!!

其次,应该把save()的调用放在循环体的外面,否则,你试试看把循环进行
1000000000000000次,看你的硬盘伤不伤!

最后
for(i=0;i<=SIZE;i++)
{
fread(&emp[i],LEN,1,fp);
printf("%-8s %-6s %4d %4d %4d\n",emp[i].name,emp[i].department,emp[i].basepay,emp[i].allowance,emp[i].total);
}

循环结束控制语句竟然用了i<=SIZE,运行没提示出错,你真是幸运了。

还补充一下,
scanf("%s,%s,%d,%d",emp[i].name,emp[i].department,emp[i].basepay,emp[i].allowance);
这样输入是不妥的,scanf不知道你输入的","是作为分隔还是字符串的内容,最好还是分开三次输入为妙:
scanf("%s",emp[i].name);
scanf("%s",emp[i].department,);
scanf%d,%d",emp[i].basepay,emp[i].allowance);
至于用%d还是%f,自己想想。