C ++复合兴趣练习

时间:2014-08-24 16:10:16

标签: c++

我是初学者,正在尝试使用“C ++ Primer Plus Sixth Edition”学习C ++。

我正在第5章,越过循环。无论如何,我正在从书中做这个编程练习,问题是:

  达芙妮以10%的简单利息投资100美元。也就是说,每年投资都会获利   原始投资的10%,或每年10美元:   兴趣= 0.10×原始余额   与此同时,Cleo以5%的复利投资100美元。也就是说,利息为5%   目前的余额,包括之前增加的利息:

     

兴趣= 0.05×当前余额

     

Cleo第一年的收入为100美元的5%,给她105美元。第二年,她获得了5%的收入   105美元,或5.25美元,等等。写一个程序,找出它需要多少年   克莱奥的投资价值超过了达芙妮投资的价值   显示当时两种投资的价值。

以下是我为此练习编写的代码,但我没有取得好成绩。 已编辑代码:

#include <iostream>
#include <array>

double Daphne(int, double, double);
double Chleo(double, double);

int main() {
    using namespace std;
    int p = 100; //Principle
    double i1 = 0.1; // 10% interest rate
    double i2 = 0.05; // 5% interest rate
    double dInv = 0; //Daphnes investment
    double cInv = 0; // Chleos investment
    int t=1; //Starting at year 1
    double s1 = 0; //Sum 1 for Daphne
    double s2 = 0; // Sum 2 for Chleo

    s1 = p + 10; //Initial interest (base case after year 1) for Daphne
    s2 = p + (i2*p); //Initial interest (base case after year 1) for Chleo

    do{
        dInv = Daphne(p, i1, s1);
        cInv = Chleo(i2, s2);
        t++;
    } while (cInv < dInv);

    cout << "The time taken for Chleos investment to exceed Daphnes was: " 
    << t << endl;
    cout << "Daphnes investment at " << t << " years is: " << dInv << endl;
    cout << "Chleos invesment at " << t << " years is: " << cInv << endl;

    system("pause");
    return 0;

}

double Daphne(int p, double i, double s1) {
    s1 = s1 + (p*i);
    return s1;
}

double Chleo(double i, double s2){
    s2 = s2 + (s2*i);
    return s2;
}

编辑:从控制台获取无输出。怀疑它永远不会从循环中断开。

最终编辑:

使用for循环计算它并在main中工作,而循环和函数调用让我感到困惑。感谢所有评论,这是我感兴趣的任何人的最终代码:

#include <iostream>
#include <array>

int main() {
    using namespace std;

    int p = 100;
    double dInv = p; //Daphnes investment
    double cInv = p; //Cleos investment
    int t; //Time 
    double i1 = 0.1; //10% interest
    double i2 = 0.05; //5% interest 

    for (t = 0; cInv <= dInv; t++) {
        dInv = (p*i1) + dInv; //Simple interest for Daphne
        cInv = (cInv *i2) + cInv; //Compund interest for Cleo
    }
    cout << "Time taken for Cleos investment to exceed Daphnes: " << t << endl;
    cout << "Daphnes investment: " << dInv << endl;
    cout << "Cleos investment: " << cInv << endl;

    system("pause");
    return 0;
}

感谢您阅读

2 个答案:

答案 0 :(得分:1)

dInv为0. cInv也是0. 0 < 0,这是假的,因此while循环退出。您可以使用以下方法解决当前问题:

while (cInv <= dInv) 

答案 1 :(得分:0)

#include <iostream> 
int main()

{
    int counter = 0;

    for (int balance1 = 100, balance2 = 100; balance2 <= balance1; balance1++ , balance2++)
    {

        balance1 += 10;
        balance2 *= 1.05;
        counter++;

    }
    std::cout << counter << " years" << std::endl;
    return 0;
}