当我输入“ -1”时,程序不会停止,而是转到以下“ printf”。为什么?

时间:2018-08-08 15:26:34

标签: c

#include <stdio.h>

int main()
{

    float gallons, miles, tot=0, cont=0, average=0, division;

    while(gallons != -1){
        printf("Enter the gallons used (-1 to end): ");
        scanf("%f", &gallons);
        printf("Enter the miles driven: ");
        scanf("%f", &miles);
        division = miles/gallons;
        printf("The miles / gallon for this tank was %.2f\n", division);
        cont++;
        tot+=division;
    }

    average=tot/cont;

    printf("The overall average miles / gallons was %.2f\n", average);

    return 0;
}

当我输入“ -1”时程序不会停止,而是转到以下“ printf”。为什么?

1 个答案:

答案 0 :(得分:1)

也许您正在寻找类似下面的内容。

 #include <stdio.h>

    int main()
    {

        float gallons =0, miles= 0, tot=0, cont=0, average=0, division;

      printf("Enter the gallons used (-1 to end): ");
            scanf("%f", &gallons);

        while(gallons != -1){

            printf("Enter the miles driven: ");
            scanf("%f", &miles);
            division = miles/gallons;
            printf("The miles / gallon for this tank was %.2f\n", division);
            cont++;
            tot+=division;

    printf("Enter the gallons used (-1 to end): ");
            scanf("%f", &gallons);
        }

        average=tot/cont;

        printf("The overall average miles / gallons was %.2f\n", average);

        return 0;
    }
相关问题