C++ for 循环不会更改变量

C++ for-loop wont change variable

本文关键字:改变 变量 for 循环 C++      更新时间:2023-10-16

**这是我的代码,我希望每次迭代都会更改值(它应该减少,因为它是系列借用)。我在MacOS上的Xcode中运行它。**

void calculateSeries(){
int loan;
cout<<"Total loan as of today:n";
cin>> loan;
int series;
cout<<"Number of seriesn";
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) interestint 的类型是整数除法,并且 - 一旦interest的值被<100,将始终导致0,因为结果的任何小数部分都将被丢弃(例如,参见这个在线C++标准草案):

5.6 乘法运算符

  1. 。对于积分操作数,/运算符产生代数商与任何 丢弃的小数部分

因此,项 (interest/100)*(loan-(loan/series)*i) 也将0,以便您的结果将在每次迭代中(loan/series)+0

(interest/100.)(请注意100.中的.,使第二个参数成为浮点值),以便该项将是浮点除法(而不是整数除法)。

顺便说一句:无论如何,loaninterest可能应该有类型 double 而不是int