来个简单的C++程序计算投资收益

in #cn-stem5 years ago (edited)

一(四十七)中说到积少成多,如果能坚持每天1%的收益,70天后翻倍,一年以后37倍。虽然用Excel很容易计算,但能否编个小程序呢?

说干就干,以前学过一点C++,试着写一个:

int main()

{
cout<<"What's your initial investment, percent profit and investment days?"<<endl;

float initial, interest, time, final;

cin>>initial>>interest>>time;

final=initial*pow(1+interest/100,time);

cout<<"You will have $"<<final<<" after "<< time <<" days!"<<endl;
}

用g++编译一下,成功了!运行一下,还是按照初始投资1000元,每天收益1%。

Picture110.jpg

算对了,70天后变成2000元,翻倍。

再算一下一年会如何:

Picture111.jpg

又对了,跟用Excel的结果是一样的。365天后的收益是37倍。那如果每天1.5%的收益,一年后会如何呢?

Picture112.jpg

将近230倍!这画面太美,不敢看了。还是看看这个简单的程序是如何运行的吧。

cout<<"What's your initial investment, percent profit and investment days?"<<endl;

这一句cout就是输出,提示用户输入初始投资,每天的利润,和投资的天数。

float initial, interest, time, final;

C和C++里面的变量必须要先定义才能使用,所以定义一下这几个float变量。

cin>>initial>>interest>>time;

读取用户的输入。

final=initial*pow(1+interest/100,time);

计算投资收益,计算公式在一(四十七)里面已经做了阐述。

cout<<"You will have $"<<final<<" after "<< time <<" days!"<<endl;

这最后一句就是输出结果啦。

最后,还有一点千万别忘了,因为计算过程中调用了数学pow函数,所以得加上

#include <math.h>

一个简单的C++程序就这样完成了。能用Excel干的事情,搞个C++来解决倒也是一件蛮好玩的事情。

Sort:  




This post has been voted on by the SteemSTEM curation team and voting trail in collaboration with @curie.

If you appreciate the work we are doing then consider voting both projects for witness by selecting stem.witness and curie!

For additional information please join us on the SteemSTEM discord and to get to know the rest of the community!

Coin Marketplace

STEEM 0.27
TRX 0.11
JST 0.033
BTC 63900.26
ETH 3063.07
USDT 1.00
SBD 4.21