微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java通货膨胀计算器问题没有正确四舍五入

如何解决Java通货膨胀计算器问题没有正确四舍五入

提示:很难做出跨越几年的预算,因为价格不稳定。 如果您的公司每年需要 200 支铅笔,您不能简单地使用今年的价格 就像两年后铅笔的成本一样。由于通货膨胀,成本可能 比今天高。编写一个程序来衡量一个项目的预期成本 指定的年数。程序询问物品的成本、数量 从现在起购买该物品的年数以及通货膨胀率。这 然后程序输出指定期间后物料的估计成本。 让用户以百分比形式输入通货膨胀率,例如 5.6(百分比)。您的 然后程序应该将百分比转换为分数,例如 0.056 并且应该 使用循环来估计根据通货膨胀调整的价格。

代码

    import java.util.Scanner;
    import java.text.NumberFormat;

    public class Inflationcalculator {

        public static void main(String[] args) {
     
           Scanner console = new Scanner(system.in);
   
           System.out.print("Enter price of the Item:");
           double cost = console.nextDouble();
    
           System.out.print("Enter number of years in which it will be purchased:");
           double years = console.nextDouble();
    
           System.out.print("Enter percent of inflation per year:");
           double inflationRate = console.nextDouble();       
     
           inflationRate = inflationRate / 100;
   
           for(int i = 1; i <= years; i++){
           cost += cost * inflationRate;
        }
   
      System.out.println(cost);
     }   
 }

预期结果:

输入·价格·of·the·Item:200↵ 输入·数量·年·年·在·哪个·它将·将·被·购买:50↵ Enter·percent·of·inflation·per·year:5↵ 2293.4799571507338

我得到了什么:

输入·价格·of·the·Item:200↵ 输入·数量·年·年·在·哪个·它将·将·被·购买:50↵ Enter·percent·of·inflation·per·year:5↵ 2293.479957150734

我不知道为什么它没有正确四舍五入,我做错了什么???

解决方法

问题:

double 变量类型的精度约为 15-16 decimal points。这就是您的结果被截断的原因。

解决方案:

您可以改为使用 BigDecimalDecimalFormat,如 these answers.

中所述 ,

此代码应该可以正常工作:

    Scanner console = new Scanner(System.in);

    System.out.print("Enter price of the Item:");
    BigDecimal cost = new BigDecimal(console.nextDouble());

    System.out.print("Enter number of years in which it will be purchased:");
    int years = console.nextInt();

    System.out.print("Enter percent of inflation per year:");
    BigDecimal inflationRate = new BigDecimal(console.nextDouble());

    inflationRate = inflationRate.divide(new BigDecimal(100));
    
    for(int i = 1; i <= years; i++) {
        cost = cost.add(cost.multiply(inflationRate));
    }

    System.out.println(cost);

输出(使用您的输入):2293.4799571507352069702827102422103183593712979003728316020223783073817003241856582462787628173828125000

如果你想把这个数字四舍五入到你的预期结果,你可以使用

System.out.println(cost.setScale(10,BigDecimal.ROUND_CEILING)); // to round up
// or
System.out.println(cost.setScale(10,BigDecimal.ROUND_FLOOR)); // to round down

.setScale() 的第一个参数是要显示的十进制数字的位数。 (抱歉我的英语不好哈哈)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。