我正在尝试制作一个程序,询问您练习了多少天,然后每天询问您制作了多少航班,然后确定每天的航班平均值,这是我现在的代码:
#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;
}
现在我到达我输入#1航班的时间部分,但是当我输入一个值时,程序停止工作,我无法继续,所以我不确定我之后是否有任何其他问题。任何帮助将不胜感激,因为我是新手! 举个例子,最终输出应该是这样的:
你练了几天?
2
第1天完成了多少次航班?
2
1号航班有多长时间?
5.00
2号航班有多长时间?
10.00
第1天:平均距离是7.500。
第2天完成了多少次航班?
3
1号航班有多长时间?
7.50
2号航班有多长时间?
13.00
3号航班有多长时间?
15.75
第2天:平均距离为12.083。
答案 0 :(得分:2)
你在两个循环(天和飞行)中使用相同的变量(i
),因此在内循环中覆盖它,使用不同的变量,你应该设置。
编辑:
此外,您应该更改一行:
printf("How long was flight #%d?\n", i++);
要:
printf("How long was flight #%d?\n", i+1);
答案 1 :(得分:0)
您的代码中出现了一些错误。我已经在下面粘贴了修改过的代码,并且还提到了您犯错误的评论,以便您可以轻松理解。
#include <stdio.h>
int main()
{
int days, flights, i,j;
double length, total = 0, 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(j=1; j<=flights; j++)
{
//in this loop you are using same int i which is already used in first for loop and alo u r incrementig it.
// so need to use another int variable.
printf("How long was flight #%d?\n", j);
scanf("%lf", &length);
// u r copying total to length ,but total is not initialized anywhere.
// it should be like this.
total += length;
}
// and u have to print average value after completion of loop.
total = total/flights;
printf("Day #%d: The average distance is %.3lf\n", i, total);
total = 0;
}
return 0;
}
希望这会对你有所帮助。