gpt4 book ai didi

java - 如何在唯一迭代中从循环中提取值?

转载 作者:行者123 更新时间:2023-12-01 11:54:47 24 4
gpt4 key购买 nike

因此,在我的 Java 简介书中,我的任务是:

Suppose that the tuition for a university is $10,000 this year and increases 5% every year. In one year, the tuition will be $10,500. Write a program that computes the tuition in ten years and the total cost of four years' worth of tuition after the tenth year.

我可以很容易地计算出第十年的学费,但让我困惑的是如何将第 11、12、13 和 14 年的独特学费值相加。如果我是对的,加起来应该是 73717.764259。我的代码给我的是 158394.52795515177。随着代码的发展,可能只是我以错误的方式思考这个问题,并且我的代码正确地进行了添加,但我认为我在这里更正确。这是我现在使用的代码:

    double initialTuition = 10000;
final double theRate = 0.05;

for (int i = 1; i < 15; i++) {
initialTuition = ((theRate * initialTuition) + initialTuition);
System.out.println("Year " + i + " tuition is: " + initialTuition);
while (i == 10){
System.out.println("Year " + i + " tuition is: " + initialTuition);
double startOfFourYearTuition = initialTuition;
System.out.println(startOfFourYearTuition);
break;
}

while ((i > 10) && (i < 15)) {
System.out.println("Year " + i + " tuition is: " + initialTuition);
initialTuition += initialTuition;
break;
}

}

最后一个 while 循环是我尝试添加 4 年。

重申一下这个问题:我怎样才能在迭代 11 到 14 处提取 initialTuition 的唯一值并添加它们?

最佳答案

那里还有很多无用的代码,for 循环内部的 while 循环等。试试这个大小:

public static void main(String[] args) 
{
double initialTuition = 10000;
double summarizedTuition = 0;

final double theRate = 0.05;

for (int i = 1; i < 15; i++) {
initialTuition = ((theRate * initialTuition) + initialTuition);
System.out.println("Year " + i + " tuition is: " + initialTuition);

if ((i > 10) && (i < 15))
{
summarizedTuition += initialTuition;
}
}

System.out.println("Summarized tuition for years 11 - 14: " + summarizedTuition);
}

输出为:

Year 1 tuition is: 10500.0
Year 2 tuition is: 11025.0
Year 3 tuition is: 11576.25
Year 4 tuition is: 12155.0625
Year 5 tuition is: 12762.815625
Year 6 tuition is: 13400.95640625
Year 7 tuition is: 14071.0042265625
Year 8 tuition is: 14774.554437890625
Year 9 tuition is: 15513.282159785156
Year 10 tuition is: 16288.946267774414
Year 11 tuition is: 17103.393581163135
Year 12 tuition is: 17958.56326022129
Year 13 tuition is: 18856.491423232354
Year 14 tuition is: 19799.31599439397
Summarized tuition for years 11 - 14: 73717.76425901074

关于java - 如何在唯一迭代中从循环中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28531106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com