首页 > 解决方案 > 如何在不停止循环的情况下创建在循环中的某个点触发的输出?

问题描述

我正在尝试为我从 OOJ 类返回的作业整理正确的代码,我们正在使用 Java。

我正在努力解决两个问题。首先,我需要该程序使用提供的比率 (6%) 计算复合增长率,并在 24 个月的过程中每次迭代打印以控制每个月的生产。其次,我需要显示生产超过7000的月份。我的教授告诉我生产应该在第10个月超过7000,我的显示更早。

我的计算中有问题,我不确定我忽略了什么。我将不胜感激有关如何改进代码的任何输入和一般建议。

弗里蒙特汽车厂发现,工人工作的时间越长,工人可以生产的零件就越多。编写一个应用程序,计算并显示一个工人在 24 个月内每个月的预期产量,假设该工人开始生产 4,000 个零件并每月将产量提高 6%。还要显示生产超过 7,000 个零件的月份(当工人应该加薪时!)。

public class IncreasedProduction {

    public static void main(String[] args) {
        //declare variables
        
        double rate = .06;
        double production = 4;
        
        //column titles
        System.out.println("(Parts produced measured in thousands)\n\n"+ "Month" + "   " + "Parts Produced\n");
        
            //counts the number of each iterations
            for(int month = 1; month > 0; month++)
            {   
                production = production*Math.pow(1.0 + rate, month);                                
                
                //displays the monthly total parts produced
                if( month < 25 )
                {
                    //Displays monthly total
                    System.out.println("  " + month + "      " + String.format("%.2f",production) + "\n");
                    
                    //calculates the moment when 7000 parts are first produced and displays a message
                    if( production >= 7 && (production/1.06) < 7) {
                        System.out.println(">>>  You produced 7000 parts in " + month + " months, you deserve a raise. <<<\n");
                }}
                else
                {   //displays number of month and total parts produced at the end of 24 months
                    
                    System.out.println("\nIn " + month + " months you produced " + String.format("%.2f",production) + " parts!");
                    //break
                    month = -1;
                
                }
            }       
    }
}

标签: javaloopsconditional-statements

解决方案


产量增加的计算似乎不正确:

production = production*Math.pow(1.0 + rate, month);

因为它将增加量乘以两倍:

  1. K = (1 + r)^月
  2. 产量 = 产量 * K

因此,在第一个月之后,月产量增长显着增长,这在将 delta 和增加计算添加到输出后很明显:

delta=240 -> 6.00%    1      4240.00
delta=524 -> 12.36%    2      4764.06
delta=910 -> 19.10%    3      5674.08
delta=1489 -> 26.25%    4      7163.39
>>>  You produced 7000 parts in 4 months, you deserve a raise. <<<

这可以通过更正来解决,以仅计算一次增加:

 production = Math.round(production*(1.0 + rate));
// or equivalent
// production = Math.round(4000*Math.pow(1.0 + rate, month));

输出

Month   Parts Produced

  1      4240.00
  2      4494.00
  3      4764.00
  4      5050.00
  5      5353.00
  6      5674.00
  7      6014.00
  8      6375.00
  9      6758.00
  10      7163.00

>>>  You produced 7000 parts in 10 months, you deserve a raise. <<<

  11      7593.00

推荐阅读