**这是我的代码,我希望每次迭代中值的更改(因为它是系列贷款,因此应减少)。我在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

最佳答案

表达式(interest/100)interest类型为int是整数除法--一旦interest的值是<100,将始终生成0,因为结果的任何小数部分都是废弃(例如,参见this在线C ++标准草案):


  5.6乘法运算符
  
  
  ...对于整数操作数,/运算符可得出具有以下条件的代数商
  小数部分丢弃
  


因此,术语(interest/100)*(loan-(loan/series)*i)也将为0,这样,每次迭代时您的结果将为(loan/series)+0

写下(interest/100.)(注意.中的100.,使第二个参数成为浮点值),这样该术语将是浮点除法(而不是整数除法)。

顺便说一句:loaninterest可能应该始终使用double类型而不是int

关于c++ - C++ for循环不会更改变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54196132/

10-10 08:08