我需要创建一个应该像这样的程序:
“每个人都留出一定数量的钱用于捐献,并将这笔钱平均分配给所有他/他所赠予的人。不存在零用钱。如果赠与人决定在2个朋友中分配5个,则他们每人将得到2个,剩下1个在赠送者的“帐户”中。
给定一组n个朋友,组中每个人花在礼物上的钱,以及每个人给礼物的朋友的清单,您的目标是确定每个人给的钱多于他们收到的钱。”
它应该从名为gift.txt的文件中读取其输入。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
char name[11];
int received;
int given;
} ppl;
int main()
{
FILE *file = fopen("D:\\Leo\\C Programs\\gift-giving\\gift.txt", "r");
int n, i, j, k, amt, ng, gift, amtgvn, diff;
char temp[11];
char temp2[11];
ppl friends[10];
fscanf(file, "%d", &n);
for(i=0; i<n; i++)
{
fscanf(file, "%s", temp);
strcpy(friends[i].name, temp);
}
for(i=0; i<n; i++)
{
fscanf(file, "%s", temp);
fscanf(file, "%d %d", &amt, &ng);
gift = amt/ng;
for(j=0; j<ng; j++)
{
fscanf(file, "%s", temp2);
for(k=0; k<n; k++)
{
if(strcmp(friends[k].name, temp2)==0)
{
friends[k].received = gift;
if(friends[k].received != 0)
{
friends[k].received += gift;
}
}
}
}
for(j=0; j<n; j++)
{
amtgvn = gift*ng;
if(strcmp(friends[j].name, temp)==0)
{
friends[j].given = amtgvn;
}
}
}
for(i=0; i<n; i++)
{
diff = friends[i].received - friends[i].given;
printf("%s %d", friends[i].name, diff);
}
fclose(file);
return 0;
}
我尝试了一个包含以下内容的gift.txt文件:
5
ryan
becky
owen
joel
mimi
ryan
200 3
becky
owen
joel
owen
500 1
ryan
mimi
150 2
joel
owen
becky
0 2
mimi
joel
joel
0 0
输出应该看起来像:
ryan 302
becky 66
owen -359
joel 141
mimi -150
但是,每当我尝试运行它时都会出错。出现一条消息,说明程序已停止运行(我在Windows上使用代码块)。
代码中似乎是什么问题?
最佳答案
该错误是由0
除以引起的。输入文件的最后一行显示为:
0 0
读取这些数字后,
amt = 0
和ng = 0
。然后继续计算amt/ng
,这将导致异常。如果
ng = 0
,则需要添加代码来避免该操作。你可以加
if ( ng == 0 )
{
continue;
}
就在行前
gift = amt/ng;
您还将使用未初始化的变量,这会导致未定义的行为。
这是更新的
main
。int main()
{
char inputFile[] = "D:\\Leo\\C Programs\\gift-giving\\gift.txt";
FILE *file = fopen(inputFile, "r");
int n, i, j, k, amt, ng, gift, amtgvn, diff;
char temp[11];
char temp2[11];
ppl friends[10];
fscanf(file, "%d", &n);
for(i=0; i<n; i++)
{
fscanf(file, "%s", temp);
strcpy(friends[i].name, temp);
friends[i].received = 0;
friends[i].given = 0;
}
for(i=0; i<n; i++)
{
fscanf(file, "%s", temp);
fscanf(file, "%d %d", &amt, &ng);
printf("name: %s\n", temp);
printf("amount: %d, ng: %d\n", amt, ng);
if ( ng == 0 )
{
continue;
}
gift = amt/ng;
for(j=0; j<ng; j++)
{
fscanf(file, "%s", temp2);
for(k=0; k<n; k++)
{
if(strcmp(friends[k].name, temp2)==0)
{
friends[k].received += gift;
}
}
}
for(j=0; j<n; j++)
{
amtgvn = gift*ng;
if(strcmp(friends[j].name, temp)==0)
{
friends[j].given = amtgvn;
}
}
}
for(i=0; i<n; i++)
{
diff = friends[i].received - friends[i].given;
printf("name: %s, received: %d, given: %d, diff: %d\n",
friends[i].name,
friends[i].received,
friends[i].given,
diff);
}
fclose(file);
return 0;
}