1
    printf("Enter the number of gallons used for tank#1: ");
    scanf("%.f", &number);
    while ((c = getchar() != '\n') && c != EOF);
    printf("Enter the number of miles driven:");
    scanf("%.f", &y);
    while ((c = getchar() != '\n') && c != EOF);
    div = number / y;
    printf("***The miles per gallon for this tank is %d\n\n", number, y, div);

I am using a for loop here, the only problem I have with this section is the division of number and y.

Every time I try to do so the result isn't calculated, it'll give me a random number or an extremely long number.

chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

0

The printf() function is wrong, because the format code if %d instead of %f. Most probably all your variables are double, but you don't show us this important information.

printf("***The miles per gallon for this tank is %f\n\n", div);

Please try it.

the busybee
  • 10,755
  • 3
  • 13
  • 30
Oscarhn27
  • 1
  • 1
0

There are multiple problems in your code:

  • you did not post the definition of number, y or div. Given the computation you want to perform and the scanf() conversion, they should be defined as float or double.

  • the scanf() conversion format is invalid: there should ve not . in %.f. Either use %f if the variables have type float or %lf if they have type double.

  • You pass 3 variables to the last printf but only one format is present %d, which is incorrect for a floating point number, leading to undefined behavior, for example a meaningless sequence of digits.

  • The division computes gallons per mile, not miles per gallon. Naming your variables with meaningful names is advisable.

Here is a modified version:

int compute_mileage(void) {
    double gallons, miles, mph;

    printf("Enter the number of gallons used for tank#1: ");
    if (scanf("%lf", &gallons) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    printf("Enter the number of miles driven: ");
    if (scanf("%lf", &miles) != 1)
        return 1;
    while ((c = getchar() != EOF) && c != '\n')
        continue;
    mph = miles / gallons;
    printf("***The miles per gallon for this tank is %f\n\n", mph);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189