janac

Calculate doubling every 5 years

Dec 2nd, 2021 (edited)
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6. // You have an investment that doubles
  7. // at the end of every 5 years.
  8. // Write a program that takes amount and years and
  9. // retuns the value of the investment.
  10.  
  11. const int yrs_to_double = 5; // Doubles at end of 5 years.
  12.  
  13. // Calculate the final value, given amount and years.
  14. float growth(float amount, float years)
  15. {
  16.     // How many 5-year periods are there?
  17.     int number_of_doublings = years / yrs_to_double;
  18.     float current_doubling = 0; // Each doubling.
  19.     for (int i = 0; i < number_of_doublings; ++i)
  20.     {
  21.         current_doubling = amount * 2; // Double it.
  22.         amount = current_doubling; // Store the doubling.
  23.     }
  24.  
  25.     return amount; // Return the final amount.
  26. }
  27.  
  28. int main()
  29. {
  30.     float amount_invested = 0; // Amount to start with.
  31.     int years_to_invest = 0; // Years invested.
  32.     float value_of_investment = 0; // Value after investing.
  33.  
  34.     cout << "Enter the amount you are investing: ";
  35.     cin >> amount_invested; // Get the starting amount.
  36.     cout << "How many years?: ";
  37.     cin >> years_to_invest; // Get the time to invest.
  38.  
  39.     // Calculate the value.
  40.     value_of_investment = growth(amount_invested, years_to_invest);
  41.  
  42.     // Show two decimal points.
  43.     cout << "After investing $" << fixed << setprecision(2)
  44.         << amount_invested << " for " << years_to_invest
  45.         << " years,\nyou now have $" << value_of_investment << ".\n";
  46.  
  47.     return 0; // End the program.
  48. }
Add Comment
Please, Sign In to add comment