c++ 不明白为什么输出不正确

9cbw7uwe  于 2023-02-10  发布在  其他
关注(0)|答案(3)|浏览(147)

我目前正在为我的C++类做一堂Zybooks课,我们将复习while循环。在这个问题中,它想让我计算一个银行账户的初始余额翻一番需要多少年。此外,还添加了一个年度贡献。我的代码如下:

#include <iostream>
using namespace std;

int main()
{  
   const double RATE = 5;
   const double INITIAL_BALANCE = 10000;
   const double TARGET = 2 * INITIAL_BALANCE;

   cout << "Annual contribution: " << endl;
   double contribution; 
   cin >> contribution;

   double balance = INITIAL_BALANCE;
   int year = 0;

   while (balance < TARGET)
   {
      year++;
      double interest = balance * RATE / 100;
      balance = balance + interest + contribution;
   }

   cout << "Year: " << year << endl;
   cout << "Balance: " << balance << endl;

   return 0;
}

我用这个作为答案,但遇到了这个意想不到的结果:

Output differs. See highlights below.

Input
100

Your output

Annual contribution: 
Year: 13
Balance: 20627.8

Expected output

Annual contribution: 
Year: 13
Balance: 20527.8
ogq8wdun

ogq8wdun1#

我看到预期的产出和你的产出相差100,也就是你的contribution。可能你的目标达到后,评估系统没有加上年贡献。下面的代码得到了你所要求的产出,但我认为你的代码应该是正确的答案。

#include <iostream>
using namespace std;

int main()
{  
   const double RATE = 5;
   const double INITIAL_BALANCE = 10000;
   const double TARGET = 2 * INITIAL_BALANCE;

   cout << "Annual contribution: " << endl;
   double contribution; 
   cin >> contribution;

   double balance = INITIAL_BALANCE;
   int year = 0;

   while (balance < TARGET)
   {
      year++;
      double interest = balance * RATE / 100;
      balance = balance + interest;
      if (balance < TARGET) {
        balance += contribution;
      }
   }

   cout << "Year: " << year << endl;
   cout << "Balance: " << balance << endl;

   return 0;
}
oxosxuxt

oxosxuxt2#

问题是,即使目标已经达到,你还是在第13年之后做出了贡献。
为了只检查一次条件,我将把它重新构造成这样:

while (true)
{
    year++;
    double interest = balance * RATE / 100;
    balance += interest;
    if (balance >= TARGET)
    {
        break;
    }
    balance += contribution;
}
1mrurvl1

1mrurvl13#

这是因为上次执行循环时(year=13),balance小于TARGET,但是在添加了contributioninterest之后,它跳出了添加了contributioninterest的循环。
因此,解决方案可以是在while循环中使用if语句来检查它是否超过TARGET;如果是的话,那就不要加贡献了。
while循环替换为以下代码:

while (balance < TARGET)
   {
      year++;
      double interest = balance * RATE / 100;
      balance = balance + interest;
      if (balance < TARGET) {
        balance += contribution;
      }
   }

相关问题