**这是我的代码,我希望每次迭代中值的更改(由于是系列贷款,因此值应减少)。我在MacOS上的Xcode中运行它。 **
void calculateSeries(){
int loan;
cout<<"Total loan as of today:\n";
cin>> loan;
int series;
cout<<"Number of series\n";
cin>>series;
int interest;
cout<<"Interest:\n";
cin>>interest;
//vector<int> loan_vector(series);
for (int i=1; i<=series; i++){
double in=(loan/series)+(interest/100)*(loan-(loan/series)*i);
//cout<<in<<"\n";
//loan_vector.push_back(in);
cout<<" Payment year " << i <<" " << in << "\n";}
}
我的输出是这样:
Total loan as of today:
10000
Number of series
10
Interest:
3
Payment year 1 1000
Payment year 2 1000
Payment year 3 1000
Payment year 4 1000
Payment year 5 1000
Payment year 6 1000
Payment year 7 1000
Payment year 8 1000
Payment year 9 1000
Payment year 10 1000
答案 0 :(得分:6)
您的表达式(interest/100)
的{{1}}类型为interest
是整数除法-一旦int
的值为interest
,将始终导致<100
,因为结果的任何小数部分都会被丢弃(例如,参见this在线C ++标准草案):
5.6乘法运算符
- ...对于整数操作数,/运算符可得出带有任何 小数部分丢弃
因此,项0
也将是(interest/100)*(loan-(loan/series)*i)
,这样在每次迭代中您的结果将是0
。
写(loan/series)+0
(注意(interest/100.)
中的.
,使第二个参数成为浮点值),这样该项将是浮点除法(而不是整数除法)
顺便说一句:100.
和loan
应该应该是interest
类型而不是double
。