【问题标题】:Math.pow not working when variable is of type int当变量为 int 类型时,Math.pow 不起作用
【发布时间】:2014-03-29 19:37:05
【问题描述】:

我的程序有一行,它根据使用Math.pow 方法的公式计算复利。

当变量loanRate在下面的程序的原始版本中被声明为Integer时,公式根本不起作用,只会返回一个0;

我将loanRate 更改为Double,如下所示,由于某种原因,现在程序正在运行。

很抱歉,如果这是一个非常简单的问题,我只是不知道为什么 Math.pow 方法不适用于我的 Int 以及使用 Math.pow 背后是否有一个我缺少的一般原则?

提前感谢您的帮助。

// Variables & Constants
int principle, i;
double simpleInt, compoundInt, difference, loanRate;

// Prompts user to enter principle and rate
System.out.print("Enter Principle: "); // keep print line open
principle = console.nextInt();
System.out.println();

System.out.print("Enter Rate: "); 
loanRate = console.nextDouble();

// Header


// Caculates and Outputs Simple, Compound and Difference for the loan
// in 5 year intervals from 5 to 30

for (i = 5; i <= 30; i = i + 5 )
{
    simpleInt = principle * loanRate/100 * i;
    compoundInt = principle * ((Math.pow((1 + loanRate/100),i))-1);
    difference = compoundInt - simpleInt;


    System.out.printf("\n %7d %7.2f %7.2f %7.2f", i, simpleInt, compoundInt, difference);
}

【问题讨论】:

  • 只是因为你在执行整数除法。

标签: java int double type-conversion


【解决方案1】:

compoundInt = principle * ((Math.pow((1 + loanRate/100),i))-1);

loanRate/100 这是关键,因为loadRate 小于 100,而这种划分的结果将为 0。将其更改为 loanRate/100.0 即可解决问题。

【讨论】:

  • 感谢一百万 - 现在非常有意义! :)
猜你喜欢
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2021-11-16
  • 1970-01-01
  • 2016-03-31
相关资源
最近更新 更多