gpt4 book ai didi

c - 嵌套循环无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:14 26 4
gpt4 key购买 nike

我正在尝试制作一个程序,询问您练习了多少天,然后每天询问您进行了多少次飞行,然后确定每天这些飞行的平均值,这是我现在的代码:

#include <stdio.h>

int main() {
int days, flights, i;
double length, total, average;

printf("How many days have you been practicing?\n");
scanf("%d", &days);

for(i=1; i<=days; i++) {
printf("How many flights were completed in day #%d?\n", i);
scanf("%d", &flights);
for(i=1; i<=flights; i++){
printf("How long was flight #%d?\n", i++);
scanf("%lf", &length);
length += total;
average = total / flights;
printf("Day #%d: The average distance is %.3lf\n", i, average);
}
}
return 0;
}

现在示例输出如下所示:

How many days have you been practicing?

2

How many flights were completed in day #1?

2

How long was flight #1?

5.00

Day #3: The average distance is 0.000.

How many flights were completed in day #2?

3

How long was flight #1?

7.50

How long was flight #3?

13.00

Day #5: The average distance is 0.000.

如您所见,目前的输出存在多个问题,未计算平均距离,我无法为每个航类输入数字,并且航类号和日期号不正确。任何帮助将不胜感激,因为我是新手!例如,最终输出应如下所示:

How many days have you been practicing?

2

How many flights were completed in day #1?

2

How long was flight #1?

5.00

How long was flight #2?

10.00

Day #1: The average distance is 7.500.

How many flights were completed in day #2?

3

How long was flight #1?

7.50

How long was flight #2?

13.00

How long was flight #3?

15.75

Day #2: The average distance is 12.083.

最佳答案

有几个问题,我对我所做的每个修复都留下了评论。如果您有任何问题,请告诉我

#include <stdio.h>

int main() {
int days, flights, i, j;
double length, total, average;

printf("How many days have you been practicing?\n");
scanf("%d", &days);

for (i = 1; i <= days; i++) {
printf("How many flights were completed in day #%d?\n", i);
scanf("%d", &flights);

// Reset total
total = 0.0;

// Use a different index variable than i, I used j
for (j = 1; j <= flights; j++) {
// Do not increment i here (I removed i++)
printf("How long was flight #%d?\n", j);
scanf("%lf", &length);

// This was probably backwards, you never assigned total
//length += total;
total += length;
}

// Compute the average per day outside the flights loop
average = total / flights;
printf("Day #%d: The average distance is %.3lf\n", i, average);
}

return 0;
}

关于c - 嵌套循环无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32752771/

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