【问题标题】:C++ Using a Recursive CallC++ 使用递归调用
【发布时间】: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 &lt;= 0 时终止。你什么时候改变过money的值?
  • 设定一个更小的目标,并学习如何使用调试器逐行执行代码..
  • 那么基本情况应该是什么?
  • @ashley_0213 我在这里得到一些输出:ideone.com/v8sweR
  • @ashley_0213 另一个错误是您正在这样做:money2 + money2 * 1.01 并且您的所有变量都是整数。该值的小数部分将被截断。

标签: c++ recursion


【解决方案1】:

让我们看看我们是否可以总结并解决这个问题:

  1. 您没有得到任何输出,因为您唯一的打印语句没有显示任何内容。
  2. 没有什么可显示的,因为当您达到 100 万美元时,您的递归例程就会直接失败而没有显示:它可以返回的唯一值是无效投资的 0。
  3. 从整数移动到浮点数。否则,100 美元小数的利息就会丢失,你会得到错误的答案。例如,少于 100 美元的投资会造成无限循环。
  4. 我认为您在递归调用中存在计算错误:增加的投资是 money,而不是 money2。我觉得这个表达式应该是

    money + money2 * 1.01
    
  5. money 是错误情况,而不是基本情况。这应该在主程序中。递归的终止情况是当投资价值达到百万美元时。或者,您可以从 100 万美元开始除以 1.01,直到达到或低于投资价值。

  6. 了解基本调试。首先,放入额外的打印语句。你有一个生病的计划;请问哪里疼。例如,在 financeRecursion 的顶部插入打印输入参数的打印语句。这将在某种程度上跟踪数据流和执行流。
  7. 使用更具描述性的变量名称。 (money,months,money2) 不明显;尝试一组更像(principal,num_period,invest_value)。这可能是您在 money2 递归中得到错误本金加法的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-14
    • 2017-04-16
    • 1970-01-01
    • 2016-03-21
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多