【发布时间】:2016-08-07 16:23:42
【问题描述】:
一家金融服务公司保证您的投资每月获得 1% 的复合回报。您想了解投资加回报总额达到 1,000,000 美元(百万美元)需要多长时间。编写一个程序,允许用户输入连续的每月投资(例如 - 每月 500 美元)或(每月 1,000 美元)。程序应调用递归方法,返回并显示达到 1,000,000 美元目标所需的总月数。
这是我目前所拥有的,程序没有显示任何内容。谢谢!
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes.
int financeRecursion(int, int, int);
int main()
{
int investment = 0;
int month = 0;
int totalMonths = 0;
cout << "Enter the amount of money you want to invest.\n\n";
cin >> investment;
totalMonths = financeRecursion(investment, month, investment); // Function call.
if (totalMonths > 0)
cout << totalMonths;
else
return 0;
} // End of main.
// Function definitions.
int financeRecursion(int money, int months, int money2)
{
if (money <= 0)
{return 0;} // Base case.
if (money2 <= 1000000)
{return financeRecursion(money,
months + 1,
money2 + money2 * 1.01);} // Recursive call.
} // End of function.
【问题讨论】:
-
看看你的基本情况。该函数只会在
money <= 0时终止。你什么时候改变过money的值? -
设定一个更小的目标,并学习如何使用调试器逐行执行代码..
-
那么基本情况应该是什么?
-
@ashley_0213 我在这里得到一些输出:ideone.com/v8sweR
-
@ashley_0213 另一个错误是您正在这样做:
money2 + money2 * 1.01并且您的所有变量都是整数。该值的小数部分将被截断。