我遇到嵌套while循环的问题。当我运行下面的代码时,我得到输出表的第一行的预期值,但不是第二行。我认为这只是一个重置balance
变量的问题,但我没有成功。
while(rate_counter < 10)
{
rate_counter = rate_counter + 1;
cout << rate;
while(time_counter < 6)
{
time_counter = time_counter + 1;
balance = investment * pow((1+ rate/100),time);
cout << "\t\t" << setw(10) << balance;
time = time + time_increment;
}
cout << endl;
balance = 0;
time_counter = 0;
rate = rate + rate_increment;
time = time + time_increment;
}
cout << endl;
return 0;
}
输出:
Rate 5 Years 10 Years 15 Years 20 Years 25 Years 30 Years
5.00 1276.28 1628.89 2078.93 2653.30 3386.35 4321.94
5.50 8513.31 11126.55 14541.96 19005.76 24839.77 32464.59
问题是第二个(以及此处的后续行)应该阅读。
5.50 1306.96 1708.14 2232.48 2917.76 3813.39 4983.95
答案 0 :(得分:1)
你几乎是对的。问题不在于balance
未被重置(它在使用之前在内部循环中设置),但time
未被重置。而不是
//...
rate = rate + rate_increment;
time = time + time_increment;
您想将时间重置为初始值:
//...
rate = rate + rate_increment;
time = time_increment;
// or maybe
// time = 0;
答案 1 :(得分:1)
您可能会发现在for循环语法中维护这些循环更容易:
unsigned int starting_rate = 500;
unsigned int ending_rate = 1050;
unsigned int rate_increment = 50;
unsigned int starting_time = 5;
unsigned int ending_time = 30;
unsigned int time_increment = 5;
for (unsigned int i = starting_rate; i <= ending_rate; i += rate_increment)
{
double rate = i / 100.0;
double balance = 0.0;
std::cout << rate;
for (unsigned int time = starting_time; time <= ending_time; time += time_increment)
{
balance = investment * std::pow((1 + rate / 100), time);
std::cout << "\t\t" << std::setw(10) << balance;
}
std::cout << std::endl;
}
从功能上讲,它是相同的,但它将所有循环维护放在一起(与你在循环中所做的逻辑分开)。