C++循环未运行时

C++ while loop not running

本文关键字:运行时 循环 C++      更新时间:2023-10-16

my while 循环不会在我设置的条件下运行。

该计划的目的是使用存款金额、利率和目标金额确定存款金额到期所需的年限。

程序在输入目标金额后停止,除非我将 while 语句从 <= 更改为>=,在这种情况下,它会运行循环,但返回设置为 100 或 1000 等的年数......

#include <iostream>
#include <iomanip>
#include <string>
#include <math.h>
using namespace std;
int main()
{
    //declare the variables
    double rate,
           balance = 0;
    int deposit,
        target,
        years = 0;
    cout << "****Lets make you some money!****" << endl << endl;
    //input from the user
    cout << "What is your deposit amount?: " << endl;
    cin >> deposit;
    cout << "What is your interest rate?: " << endl;
    cin >> rate;
    cout << "What is you target savings amount?: " << endl;
    cin >> target;
    rate = rate / 100;
    while (balance <= target); //when i change this to balance >= target the 'while' runs but just returns years divisible by 100
    {
        // calculation
        balance += deposit * pow((1 + rate), years);
        //balance = balance*(1 + rate) + deposit;   // alternate calculation
        //years++; 
        //users savings target
        cout << "You will reach your target savings amount in: " << balance << " years." << endl << endl << " That's not that long now is it?" << endl;
    }
    return 0;
}

提前感谢!

问题是一个不幸的后缀:

while (balance <= target);
//                       ^

这相当于:

while (balance <= target) {
    ;
}
{
    // calculation, which always runs exactly once
    // regardless of what balance/target are
}

只需删除分号即可。