【问题标题】:why am i getting infinity for an answer为什么我得到无限的答案
【发布时间】:2014-02-21 22:06:48
【问题描述】:

所以,我尝试了多种不同的方法,但是当我为最后一个输出运行此命令时,我仍然得到无穷大的答案,你认为问题是什么?第一个输出工作正常,但第二个和第三个没有。他的指数应该是^12*5。我不是在做math.pow 对吗?

import java.util.Scanner; 

public class CompoundInterest { 
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); 

        double principal = 0; 
        double rate = 0; 
        double time = 0; 

        double one = 0; 
        double three = 0;
        double five = 0;
        double a, b;
        System.out.print("Enter the amount of the loan: "); 
        a = input.nextDouble(); 

        System.out.print("Enter the Rate of interest : "); 
        b = input.nextDouble(); 

        one = a * Math.pow((1 + b/12),Math.pow(12,1)); 
        three = a * Math.pow((1 + b/12),Math.pow(12,1)); 
        five = a * Math.pow((1 + b/12),Math.pow(12,5)); 

        System.out.println(""); 
        System.out.println("The Compound Interest after 1 year is : " 
        + one); 

        System.out.println(""); 
        System.out.println("The Compound Interest after 3 years is : " 
        + three); 

        System.out.println(""); 
        System.out.println("The Compound Interest after 5 years is : " 
        + five); 
    }
}

【问题讨论】:

  • To the power of 12*5。为什么不直接做^60

标签: java output infinity


【解决方案1】:

您实际上是在获取两个权力,例如在第二行(五年利息):

five = a * Math.pow((1 + b/12),Math.pow(12,5));

归结为:a * (1 + b/12)^(12^5)。在普通的 32 位或 64 位计算机上,这是一个接近无穷大的数字。

尝试使用a * Math.pow((1 + b/12), 12 * years);,其中years 是利息年数。

【讨论】:

    【解决方案2】:

    你正在提升 12^5 的力量,它非常巨大,应该导致无穷大。

    试试

    five = a * Math.pow((1 + b/12), 12*5);
    

    改为。

    【讨论】:

    • 这会产生一个数字。 Here 是指向 IDEOne 的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    相关资源
    最近更新 更多