使用while循环计算每天行走的平均里程

时间:2019-04-29 22:40:27

标签: c

我无法添加输入并获得平均值的正确输出。

据我所知,下面的代码。任何帮助将不胜感激!

#include <stdio.h>

int main() {
  /* variable definition: */
   int days;
   float avg, miles;
/* Initialize */
   days=1;
// Loop through to input values

while(days<=7) {
      printf("Enter the number of miles for each day walked.");
      // use %lf for double, %f for float
      scanf("%f", &miles);
      days++;
      }

   avg = miles / days;
   printf("average is %f\n " , avg );
   return 0;
} // end main

1 个答案:

答案 0 :(得分:1)

正如John3136所说,您并没有跟踪所走的总里程。您以英里为单位进行扫描,但是您无法跟踪英里的总和。您的平均值就是您最后输入的英里数除以7。

这是一个建议的解决方案:

int main(void)
{
    // variable definition
    int days = 0;
    float avg = 0, miles = 0;

    // Loop through to input values
    while(days < 7)
    {
        printf("Enter the number of miles for each day walked: ");
        scanf("%f", &miles);
        avg += miles;
        days++;
    }

   avg /= days;
   printf("average is %.2f\n " , avg);

   return 0;
}

在Jonathan Leffler的帮助下,这是先前代码的增强版本:

#include <stdio.h>

int main(void)
{
    // variable definition
    int days = 0;
    double miles = 0.0, total_miles = 0.0;

   // Loop through to input values
    while(days < 7)
    {
        printf("Enter the number of miles for day %d: ", days + 1);

        if(!scanf("%lf", &miles))
            return -1;

        total_miles += miles;
        days++;
    }

   printf("Total miles: %.2lf / %d Days = %.2lf Average miles per day.\n",
           total_miles, days, (days > 0) ? total_miles / days : 0.0);

   return 0;
}