C++ for 循环不会更改变量
C++ for-loop wont change variable
**这是我的代码,我希望每次迭代都会更改值(它应该减少,因为它是系列借用)。我在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)
interest
是 int
的类型是整数除法,并且 - 一旦interest
的值被<100
,将始终导致0
,因为结果的任何小数部分都将被丢弃(例如,参见这个在线C++标准草案):
5.6 乘法运算符
- 。对于积分操作数,/运算符产生代数商与任何 丢弃的小数部分
因此,项 (interest/100)*(loan-(loan/series)*i)
也将0
,以便您的结果将在每次迭代中(loan/series)+0
。
写(interest/100.)
(请注意100.
中的.
,使第二个参数成为浮点值),以便该项将是浮点除法(而不是整数除法)。
顺便说一句:无论如何,loan
和interest
可能应该有类型 double
而不是int
。
相关文章:
- 变量没有改变?通过向量的函数调用
- 在向量内更改变量的值不会改变其在向量外的值
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 标准在哪里定义了可变变量可以改变
- C++11:可变的 lambda 似乎没有改变变量?
- printf() 似乎改变了一个变量
- 为什么我的变量在单独的线程中修改时没有改变?C++/boost
- 为什么 Player.x 和 Player.y 变量没有改变?
- C - 如何将各处的静态函数称为改变其私有变量
- 即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
- 为什么调用 CUDA 内核函数时这个类成员变量没有改变
- 全局变量的顺序会改变C /OpenGL的性能
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 如何在C++中改变超类和子类的变量
- setRoomName不会改变变量roomName
- 不能改变变量的值
- 是否有一种方法可以改变变量在内存中的存储方式(位大小)
- Std::cout改变变量的值
- 使用引用改变变量的地址