Thread: Creating a function to covert gallons to liters and help with functions in general

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    10

    Creating a function to covert gallons to liters and help with functions in general

    Hello everyone, I'm in an intro to programming class and look forward to using this site in the future. One issue I'm having is i need to make a function to convert gallons to liters, however, there are still some basics regarding functions and even basic programming fundamentals that I am unclear on.

    I have some questions in this code that some of you might be able to answer.

    1. What is "MAXCOUNT 4" what is the sole purpose of this? Why is it needed?

    2. Can I take out the for(count = 1; count <= MAXCOUNT; count++)

    3. I am having trouble understanding the overall structure of this function.

    4. What is the purpose of %6.2f in "printf("The liters equivalent is %6.2f\n", (5.0/9.0) * (inGallons / 3.7854) );"




    Code:
    #include <stdio.h>
    int main()
    {
      #define MAXCOUNT 4
    
      void gallonsToLiters(float );
    
      int count;             
      float gallons;
    
      for(count = 1; count <= MAXCOUNT; count++)
      {
        printf("Enter an amount of Liquid in gallons: ");
        scanf("%f", &gallons);
        gallonsToLiters(gallons);
      }
    
      return 0;
    }
    
    void gallonsToLiters(float inGallons) /* function header */
    {
      printf("The liters equivalent is %6.2f\n", (5.0/9.0) * (inGallons * 3.7854) );
    }

  2. #2
    Registered User
    Join Date
    Jan 2007
    Location
    Euless, TX
    Posts
    144
    Any decent 'C' book will provide you all the answers you seek here. You should already have one if you're taking a class in 'C'.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    It appears that you have pasted code for another program to utilize it in your program. you will come across things that you don't understand when you do it that way. Also, you asked if you can take the for loop out?: don't be afraid to take things out and see what happens. It's just software, it won't break. From the looks of it, you don't need a loop or the maxcount. But keep in mind you are just creating a function, functions are only a part of the whole. you'll need to have an understanding of the purpose of the rest of the program before you can determine if you need it. Also your gallonsToLiters printf statement includes the formula statement. I would recomend separating the statement and your output(printf) statement. Code should be simple and readable. but you are on the right track.

Popular pages Recent additions subscribe to a feed

Tags for this Thread