因此,在我的java书介绍中,我的任务是:
假设今年大学的学费为10,000美元,每年增加5%。在一年内,学费将为10,500美元。写一个计算十年学费的计划和十年后四年学费的总费用。
我可以很容易地计算出第十年的学费,但令我难过的是如何在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;
}
}
最后一次循环是我尝试添加4年。
重申一个问题,如何在迭代11到14中提取initialTuition的唯一值并添加它们?
答案 0 :(得分:1)
你也有很多无偿的代码,而for循环内部的循环等等。试试这个大小:
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
答案 1 :(得分:0)
double theRate = 1.05; // rate of increase +5%
double tuitionCost = 10000; // base cost
double fourYearCost = 0; // four year cost (years 10-13)
for (int i = 0; i <= 13; i++) {
System.out.println("Cost of year: " + i + " is $" + tuitionCost); // print out this years cost
if(i >= 10){ //if its year 10, 11, 12, 13
fourYearCost += tuitionCost; // add this years tuition cost
}
tuitionCost *= theRate; // increment the tuition (mutiply it by 1.05, or 5% increase)
}
System.out.println("Cost of tuition for years 10, 11, 12, 13: $" + fourYearCost); // print the cost for the remaining years