我的while循环不会在我设置的条件下运行。
该计划的目的是使用存款金额,利率和目标金额确定存款金额到期的年数。
程序在输入目标金额后才会停止,除非我将while语句从< =更改为> =在这种情况下它运行循环但返回在第100轮设置的年数#s或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;
}
提前致谢!
答案 0 :(得分:12)
问题是一个不幸的后缀:
while (balance <= target);
// ^
这相当于:
while (balance <= target) {
;
}
{
// calculation, which always runs exactly once
// regardless of what balance/target are
}
只需删除分号。