C 程序不会正确划分两个 scanf 输入

C program will not divide two scanf inputs correctly

我正在尝试创建一个程序,该程序接受用户使用的加仑数和三个油箱行驶的英里数的输入以进行分配。我遇到的问题是 for 循环要么没有正确地将输入中的两个值除以第三个值(每加仑平均英里数),要么程序没有正确处理输入。但是我对此还是个新手,所以我不确定问题出在哪里。


    for(i = 1; i <= 3; ++i)
    {
        /* Define calculations */
        /* ------------------- */

        ave_miles = miles / gallons;
        total_miles = total_miles + miles;
        total_gallons = total_gallons + gallons;
        total_ave_miles = total_miles / total_gallons;

        /* Propmpt user for miles and gallons used and calculate miles per gallon. */
        /* ----------------------------------------------------------------------- */

        printf("Enter the number of gallons used for Tank #%i: ", i);
        scanf("%f", &gallons);
        while ( (c = getchar() != '\n') && c != EOF);

        printf("Enter the number of miles driven: ");
        scanf("%f", &miles);
        while ( (c = getchar() != '\n') && c != EOF);

        printf("*** The miles per gallons for this tank is %.1f\n\n", ave_miles);
    } /* end for loop */

    /* Display and calculate the total miles per gallon for the three tanks. */

    printf("Your overall average of miles per gallon for three tanks is %.1f\n\n", total_ave_miles);
    printf("Thank You for using the program. Goodbye.\n");

} /* end main */

C 和 C++ 没有惰性求值。所以如果你这样做:

ave_miles = miles / gallons;
scanf("%f", &miles);
scanf("%f", &gallons);
printf("%f\", ave_miles);

它不会给你 miles / gallons 的平均值。

相反,第一行将 分配 miles / gallons 的除法与这些变量在特定时刻的值(即 0.0 / 0.0,将生成 而不是数字 NaN)。

您想这样做:

scanf("%f", &miles);
scanf("%f", &gallons);
ave_miles = miles / gallons;
printf("%f\", ave_miles);

现在除法 miles / gallons 将为您提供这些变量的平均值。