gpt4 book ai didi

c 组合文本文件中每一行的数字

转载 作者:行者123 更新时间:2023-11-30 15:53:33 25 4
gpt4 key购买 nike

我有一个包含很多行的文本文件,我将其中一些复制粘贴到此处以向您展示我正在使用的内容。

1 2011 年 7 月 16 日17.00 OB - FCN 2 - 0 6.965
1 2011 年 7 月 17 日14.00 FCM - SIF 1 - 2 5.370

2 2011 年 7 月 23 日17.00 SIF - BIF 0 - 1 4.173
2 2011 年 7 月 23 日19.00 FCK - OB 2 - 2 14.774
3 2011 年 7 月 30 日17.00 AGF - OB 2 - 2 11.312
3 2011 年 7 月 30 日19.00 FCK - FCN 2 - 0 11.076

while (fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10)
int prev_goal = goal1 + goal2;
int current;
if(prev_goal > current) {
printf("Runde %d var den mest målrige med %d mål\n", runde, prev_goal);
}

我将这些值放入不同的变量中,但是如何将每轮的结果相加并查看哪一轮的目标最多?任何建议都会被采纳!谢谢:)

最佳答案

我将假设您只关心哪一轮的目标最多,并且您不需要像 @Ben 建议的那样将文本文件存储在内存中。

如果是这种情况,你可以这样做:

int i, maxGoals = 0, roundWithMostGoals = 0;

for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals < goal1 + goal2)
{
roundWithMostGoals = runde;
maxGoals = goal1 + goal2;
}
}

// Edit:
printf("The largest number of goals was %d, scored in round %d", maxGoals, roundWithMostGoals);

这段代码确实有问题。如果有两轮进球数最多,则仅打印第一轮。

为了避免这种情况,我们需要循环两次,这并不理想,我建议使用其他建议的方法之一,将所有这些数据加载到内存中。

但是,这里有一个类似于上面的修改后的解决方案,尽管我认为它不是最佳的:

int i, maxGoals = 0, roundWithMostGoals = 0;

// Find the maximum number of goals that was scored in any one round.
for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals < goal1 + goal2)
{
maxGoals = goal1 + goal2;
}
}

printf("The largest number of goals scored was %d.\n", maxGoals);
printf("The largest number of goals was scored in\n");

// TODO: Reposition the file stream back to the beginning or close it and then reopen it again.
// XXX Code Here XXX

// Loop through again getting all the rounds with the maximum number of goals.

for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals == goal1 + goal2)
{
printf("\tRound %d\n", runde);
}
}

但是现在这会循环两次,绝对不是解决您问题的最佳解决方案。

关于c 组合文本文件中每一行的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13556660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com