Java只打印最后一个循环值



我有以下代码:

import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
for (int x = 1; x < 6; x = x + 1) {
System.out.println(amount= amount * 9 / 10);
}
}
}

的想法是,程序接受用户输入,并计算六个月的付款与任何类型的循环。每月10%的利息从主要债务中扣除。例如,如果输入10000,输出是:

10000
9000
8100
7290
6561
5904

我只需要打印最后一个值,在本例中是5904。同样,我需要使用循环,而不是简单地计算剩余值。我如何设置循环来完成这个呢?

将print语句移出循环:

for (int x = 1; x < 6; x = x + 1) {
amount = amount * 9 / 10;
}
System.out.println(amount);

System.out.println调用移到循环外。在循环中计算金额。在循环外打印最终结果,即:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
for (int x = 1; x < 6; x = x + 1) {
amount = (amount * 9) / 10;
}
System.out.println(amount);
}

最新更新