-7

So, I made this basic loop to take user input, do some calculations with it and then after the loop breaks to display the overall average of the calculations. The problem is with the warning I am getting. Maybe I am missing something here, but I am new to this, so I don't know what the issue is. The first warning says, "Variable 'miles' is used uninitialized whenever function 'main' is called." The second warning says, "Variable 'gallons' may be uninitialized when used here." The program seems to work fine, but I just don't know how to fix the warnings. Any help is appreciated.

#include <stdio.h> //library header 
int main() { //declare main function    
    double gallons,miles;
    double sum=0;
    int count=0;

    while (miles>=0||gallons>=0) {
        sum+=(miles/gallons);
        count++;

        printf("\nEnter the gallons used (-1 to end): ");
        scanf("%lf",&gallons);

        if (gallons<0)
        break;

        printf("Enter the miles driven: ");
        scanf("%lf",&miles);

        if (miles<0)
        break;

        printf("The miles/gallon for this tank was: %lf", miles/gallons);
    }

    if (count>0) {
        printf("The average is: %lf", sum/(count-1));
    }

    return 0;
}
J...S
  • 5,079
  • 1
  • 20
  • 35
fakhri96
  • 7
  • 2
  • 5
    Read the warnings again, over and over. It'll come to you. – Some programmer dude Dec 24 '18 at 09:18
  • 1
    The warning seems descriptive enough. You've not initialised the variables `gallon` and `miles` before using their value. Consider changing the `double gallons,miles;` to something like `double gallons=0,miles=0;` – J...S Dec 24 '18 at 09:18

1 Answers1

1

Well the message is clear and it is easy to spot in your program:

double gallons,miles;

while (miles>=0||gallons>=0) {

miles is declared in a function and so is an automatic variable. Automatic variables are not initialized (so they have garbage values). Now in the first executable statement you compare miles. But miles is still uninitialized. Maybe copy the following lines to before the while? Same for gallons.

    printf("Enter the miles driven: ");
    scanf("%lf",&miles);

Note: check the return value of scanf if indeed a value was read.

BTW, you could take the habit of initializing your local variables, e.g. with double gallons = 0.0, miles = 0.0; instead of just declaring double gallons,miles;.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • also the code needs a little more restructuring like moving the `sum+=(miles/gallons);` statement to just before the `printf("the Avg is....` , to get the desired output. – yashC Dec 24 '18 at 09:24