java 控制流报表,多少年后才能达到目标金额

5uzkadbs  于 2023-01-29  发布在  Java
关注(0)|答案(4)|浏览(101)

我很想解决这个任务,但遗憾的是,我止步于此:也许我在int中计算,但应该在double中计算吗?
彼得把钱存在银行里。银行每年增加百分之一的存款。彼得想知道他在银行的存款要过多少年才能达到他的目标金额。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}

测试输入:100 15 120
正确输出:2
您的代码输出:1

8ehkhllq

8ehkhllq1#

尝试按如下所示进行更改。

int years = 0;
while (goal > money) {
    money = money + money * (percent / 100);
    ++years;
}
wgmfuz8q

wgmfuz8q2#

应将年份初始化为0,而不是-1:

int years =0;
sczxawaw

sczxawaw3#

您的代码的问题是您将年份设置为-1而不是0。这就是为什么您的代码输出计数比预期计数少1。我已相应地更新了您的代码,使其生成预期输出。请在下面找到它。如果您有问题,请告诉我。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Stackoverflow_053120 
{
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        int money = Integer.parseInt(in.readLine());
        int percent = Integer.parseInt(in.readLine());
        int goal = Integer.parseInt(in.readLine());

        int years = 0;
        while(money < goal)
        {
            money = (money * (100+percent)) / 100;
            years++;
        }
        System.out.println(years);
    }
}
bqf10yzr

bqf10yzr4#

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Stackoverflow_053120 
{
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        System.out.println("Enter money, percent and goal");
        String input[] = in.readLine().split(" ");
        int money = Integer.parseInt(input[0]);
        int percent = Integer.parseInt(input[1]);
        int goal = Integer.parseInt(input[2]);

        int years = 0;
        while(money < goal)
        {
            money = (money * (100+percent)) / 100;
            years++;
        }
        System.out.println(years);
    }
}

相关问题