计算每加仑的平均英里数

时间:2013-06-28 02:48:00

标签: c average

这里有没有C语言程序员可以帮我解决这个问题? 我无法计算每加仑平均英里数,而我的头在旋转。如果有人有解决方案我真的很感激^ _ ^

int x, number_of_tanks = 3;
double total_num1, total_num2;
double total_miles_per_gallon;
float division, avg;
float num1, num2;

for (x = 1; x <= 3; x++)
{
    printf("Enter the number of gallons used for tank #%i: ",x);
    scanf("%f", &num1);
    fflush(stdin);      /* clear input buffer */

    printf("Enter the number of miles driven: ");
    scanf("%f", &num2);
    fflush(stdin);      /* clear input buffer */

    /*--------------------------------------------------------------*/
    /* calculate and output the miles per gallon from user input.   */
    /* ------------------------------------------------------------ */

    division = num2 / (float) num1;                            
    printf("The miles per gallon for this tank %.1f divided by %.1f is %.1f", \
        num2, num1, division);

    total_num2 = total_num2 + num2;
    printf("The total of miles is %f\n", total_num2);

    total_num1 = total_num1 + num1;
    printf("The total of gallons is %f\n", total_num1);
}

avg = (double) total_num2 / total_num1; 
printf("Overall average miles per gallon for three tanks: %.1f", avg);

1 个答案:

答案 0 :(得分:1)

您没有初始化总计,因此它们未定义。当您开始添加它们时,您会得到未定义的结果。我敢打赌,这就是你的意思,它不起作用。

这样做:

double total_num1 = 0;
double total_num2 = 0;