加法运算符没有影响

addition operator has no affect

本文关键字:有影响 运算符      更新时间:2023-10-16

我正试图在for循环中添加两个浮点,它告诉我"+"没有影响。我试图让它解析两个范围(开始速率和结束速率)(1和2)和1+.25的每个增量(.25)。25工作不正常,我得到了一个无限循环

float begrate,endrate,inc,year=0;
cout << "Monthly Payment Factors used in Compute Monthly Payments!" << endl;
cout << "Enter Interest Rate Range and Increment" << endl;
cout << "Enter the Beginning of the Interest Range:  ";
cin >> begrate;
cout << "Enter the Ending of the Interest Range:  ";
cin >> endrate;
cout << "Enter the Increment of the Interest Range:  ";
cin >> inc;
cout << "Enter the Year Range in Years:  ";
cin >> year;
cout << endl;
for (float i=1;i<year;i++){
    cout << "Year:  " << "     ";
    for(begrate;begrate<endrate;begrate+inc){
        cout << "Test " << begrate << endl;
    }
}
system("pause");
return 0;

这是因为begrate+inc对begrate的值没有影响。+运算符与++运算符不同。必须将结果分配给某个对象才能产生效果。你想要的是:

begrate = begrate + inc

begrate += inc

您可以使用+=而不是+,因为这会将begrate设置为begrate+inc。更好的解决方案是有一个临时循环变量,它开始等于begrate,然后递增

for (float i=1;i<year;i++){
    cout << "Year:  " << "     ";
    for(float j = begrate;j<endrate;j+=inc){
        cout << "Test " << j << endl;
    }
}
Just replace the following line
for(begrate;begrate<endrate;begrate+inc){

with
for(begrate;begrate<endrate;begrate+=inc){

注意这里的起始值*+=*inc