gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:37 24 4
gpt4 key购买 nike

**这是我的代码,我希望在每次迭代中改变 in-value(它应该减少,因为它是一个系列贷款)。我在 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 Multiplicative operators

  1. ... For integral operands the / operator yields the algebraic quotient with any fractional part discarded

因此,术语 (interest/100)*(loan-(loan/series)*i)将是 0 ,这样你的结果也将是 (loan/series)+0在每次迭代中。

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com