嗨,我是编程新手,我想知道如何简化以下代码。有没有一种方法可以设置将更改的变量,而不是设置1-6个月?

double RATE;
double SAVING;
double MONTH1;
double MONTH2;
double MONTH3;
double MONTH4;
double MONTH5;
double MONTH6;

System.out.print("Enter the monthly saving amount: ");
SAVING = input.nextDouble();

RATE = 1.00417;

MONTH1 = SAVING * RATE;
MONTH2 = (MONTH1 + SAVING) * RATE;
MONTH3 = (MONTH2 + SAVING) * RATE;
MONTH4 = (MONTH3 + SAVING) * RATE;
MONTH5 = (MONTH4 + SAVING) * RATE;
MONTH6 = (MONTH5 + SAVING) * RATE;

System.out.println("After the sixth month, the account value is $" + (float) MONTH6);

最佳答案

您在这里做什么:

MONTH1 = SAVING * RATE;
MONTH2 = (MONTH1 + SAVING) * RATE;
MONTH3 = (MONTH2 + SAVING) * RATE;
MONTH4 = (MONTH3 + SAVING) * RATE;
MONTH5 = (MONTH4 + SAVING) * RATE;
MONTH6 = (MONTH5 + SAVING) * RATE;


是您一遍又一遍地写了本质上相同的东西。

对于类似的重复任务,循环始终是一个更好的解决方案。

使用循环,您甚至不需要所有这些MONTH变量。这是一个使用循环消除重复代码来计算totalMonths个月后的帐户值的示例:

int accountValue = 0;
int monthNumber = 0;

while (monthNumber < totalMonths) {                // Do what's inside the brackets as long as monthNumber is less than totalMonths.
    accountValue = (accountValue + saving) * rate; // Update the account value with saving and rate.
    monthNumber = monthNumber + 1;                 // Increase monthNumber by one.
}

System.out.println("After " + totalMonths + " months, the account value is $" + accountValue);


在上述代码末尾,在accountValue个月后,totalMonths将具有帐户总值。

这是一个非常简单的例子。尝试一下,并确保您100%理解它。

请注意,我用小写字母(确切地说是camelCase)来写变量名,因为它是Java中常见的naming convention

10-06 03:15