Thread: new one

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #7
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    Ok. You have too many variables.

    If you want to "make it a function" you have to define what you want this function to do.
    In math, functions have inputs and some known format of output. In programming, there doesn't have to be any inputs, and the function might DO something but not EVALUATE to anything. Still, the concept is similar. For this program, I'd make some function that takes a starting balance,a quarterly rate, and a number representing which quarter to evaluate to, and then "returns" the adjusted balance.

    Ok. It "returns" the new balance. What kind of data is that? Double. The function is a double. Let's call it qtr_calc:
    Code:
    double qtr_calc/*.....*/;
    Now let's make a function. What inputs (arguments) will it accept? I said before: a starting balance, a quarterly rate, and a quarter. The starting balance will be of the same type as the other balances, thus a double. The rates you make floats (although your constants were doubles), but I'll use a double instead. The quarter could be any number, but since this interest is compunded quarterly, saying the 1.7th quarter will yield the same result as the 1st quarter. So let's use an int.
    Code:
    double qtr_calc(double start_bal, double qtr_rate, int last_qtr);
    Hey, look! A logical funciton prototype. Now for the code.
    Code:
    double qtr_calc(double start_bal, double qtr_rate, int last_qtr)
    {
       qtr_rate += 1.0;  //might not need this, depending on usage.
    
       if(last_qtr == 0 && qtr_rate == 0.0)  return start_bal;  // prevent pow(0,0)
    
       else if(last_qtr > 4)  std::cout << "Quarterly earnings calculated beyond one year." << std::endl;
    
       return std::pow(qtr_rate,last_qtr) * start_bal;
    }
    Then you could:
    Code:
    //. . .  somewhere else, maybe in main() . . . 
    double principle, rate = .053/4.0;
    std::cin >> principle;
    std::cout << "After the third quarter, the balance is $" << std::fixed << std::setprecision(2) << qtr_calc(principle, rate, 3) << std::endl;
    //Note: principle and rate are unchanged by the function.
    And I think that oughta do it.
    Last edited by CodeMonkey; 06-12-2007 at 02:38 PM. Reason: Removing second to last line. Unnecessary.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

Popular pages Recent additions subscribe to a feed