Converting Existing Code into a Function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BelleBaby
    New Member
    • Mar 2008
    • 5

    #1

    Converting Existing Code into a Function

    I have my code all ready and everything works fine with the correct answers, but I don't know how to make functions in it. I only have the main() function at the beginning. how do I even begin to make a function? The examples they have in the book don't really help me because it's not even close to what I am doing.

    Like here is one part of my code..

    //Declare the variables
    double F, S, C, P;

    //Obtain a Fixed Cost
    while (1)
    {
    printf ("Input a fixed cost of placing/receiving an order:");
    scanf ("%lf", &F);

    //If fixed cost is less then $1, the question is asked again
    if (F<=0)
    {
    printf ("Fixed cost cannot be less then $1.\n");
    continue;
    }
    else
    break;
    }

    do I change anything to this part? or do I only focus on the calculation part?

    (calculation part)

    // Calculate the Economic Ordering Quantity (EOQ)
    double EOQ;
    EOQ = sqrt ((2*F*S)/(C*P));

    //Output value for EOQ
    printf ("The economic ordering quantity is %.2lf units.\n", EOQ);


    I know I have to come up with a function prototype (a name), but what goes before main() and where do the return values go? also, do i completly get rid of the printf statements?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    The calculation part could and probably should be made the function. Typically
    it should be declared before the main () function. Its implementation definition is is typically positioned below main. There does not need to be any difference between the function declaration name and the function definition name. That is the fuction arguements must define type with associated variable names being optional in the declaration but mandatory in the function definition name. The declaration name and arguements end with a semi-colon.
    Code:
    convert_temp(float x); //declaration, x variable identity may be ommitted.
    
    convert_temp(float x)   // function implementation - x variable identity required
      {
         //function formula in this body
         return temp;
     }

    Comment

    Working...