Thread: Caught in a Loop

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    15

    Caught in a Loop

    Hi,

    I'm working on a program that should do the following:

    Prompt a user to enter the amount of gallons used
    Prompt a user to enter the amount of miles driven
    Give the average miles / gallon

    This program should repeat this process until the user enters -1 as the sentinal value, after which the program gives the overall miles / gallon.

    I've messed the code up quite a bit, from trying to get it to work. What happens is the first prompt prints okay, but after I enter a number (12.8 in this case), the program does nothing. So if I hit enter, it prints the same line again but with the next prompt on the same line. If I hit enter again, I go into a loop. Any help is appreciated! Here's my code:

    Code:
    #include <stdio.h>
    
    int main()
    {
            float average1, average2, gallons;
            int counter,  miles;
    
            counter = 0;
    
            printf( "Enter the gallons used, -1 to end: " );
            scanf( "%f\n", &gallons );
    
            printf( "Enter the miles driven, -1 to end: ");
            scanf( "%d", &miles );
    
            while ( gallons != -1 ){
    
                    printf( "Enter the gallons used, -1 to end: " );
                    scanf( "%f", &gallons );
                    
                    printf( "Enter the miles driven, -1 to end: ");
                    scanf( "%d", &miles );
            
            while ( gallons != -1 ){
    
                    printf( "Enter the gallons used, -1 to end: " );
                    scanf( "%f", &gallons );
            
                    printf( "Enter the miles driven, -1 to end: ");
                    scanf( "%f", &miles );
    }
                    if ( counter != 0 ) {
                    average1 = ( float ) miles / gallons;
                    printf( "The average miles / gallon is %.6f", average1 );
            }
            else
                    printf( "No information was entered\n" );
    
      return 0;
    }
    Last edited by aprilbiz; 07-22-2002 at 04:02 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 02:14 AM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM