0
0

More than 3 years have passed since last update.

Javascript コーディング問題(手助け求めます)

Posted at

 Javascript のコーディング質問

Javascriptにて

あなたは現在価格mドルの土地の購入するために、年利i(0 < i < 100)%の金融商品にpドル投資しました。何年後に土地の購入ができるでしょうか?howLongToReachFundGoalという関数を再帰によって作成してください。なお、毎年得られた利益は同商品に再投資するとし、土地の価格は経過する年数が偶数(0を含む)の時は2%、奇数の時は3%上昇します。また、人の寿命は80歳未満と仮定し、80年以上かかる時は80としてください。

という内容の元プログラムを組んでいます。

問題に直面しているのですが、一定数の入力だと正解の出力より1多い数値を出してしまうのですが、改善方法がわからず行き詰まってしまっています。

(例)
入力:5421,10421,5
正解の出力:27
自分の出力:28

どなたか分かる方手助けお願いします。

function howLongToReachFundGoalHelper(capitalMoney, goalMoney, interest, x){
    function capitalAfterInterest(capitalMoney, interest, x){
        if(x == 0){
            return capitalMoney;
        } else {
            return capitalMoney * (1 + (interest / 100));
        }
    }
    function goalMoneyAfterInflation(goalMoney, x){
        if((x % 2 == 0) || (x == 0)){
            return goalMoney * 1.02;
        } else {
            return goalMoney * 1.03;
        }
    }
    if(x >= 80){
        return 80;
    } else if(capitalMoney >= goalMoney){
        return x;
    } else {
        return howLongToReachFundGoalHelper(capitalAfterInterest(capitalMoney, interest, x + 1), goalMoneyAfterInflation(goalMoney, x + 1), interest, x + 1);
    }
}

function howLongToReachFundGoal(capitalMoney,goalMoney,interest){
    //ここから書きましょう
    return howLongToReachFundGoalHelper(capitalMoney, goalMoney, interest, 0);
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0