Java 为什么 Math.pow(x,y) 算作双精度数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23326902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:57:20  来源:igfitidea点击:

Why Does Math.pow(x,y) Count as a Double?

javaintdoublepow

提问by Jason Chen

I'm writing a Java program to calculate how much food it will take to get a monster to a certain level in My Singing Monsters. When I run the program, it says, "cannot convert from double to int". Can someone explain why this is? Here's the program.

我正在编写一个 Java 程序来计算在 My Singing Monsters 中让怪物达到某个级别需要多少食物。当我运行程序时,它说“无法从双精度转换为整数”。有人可以解释为什么会这样吗?这是程序。

int totalFood = 0;
int level = 1;
int levelMeal = 5*(Math.pow(2,level-1));
int mealNumber = 1;
int levelGoal = 1;
while(level != levelGoal)
{
  if(mealNumber != 5)
  {
    mealNumber += 1;
    totalFood += levelMeal;
  }
  else if(mealNumber == 5)
  {
    mealNumber = 0;
    level += 1;
  }
}
if(level == levelGoal)
{
  println("The total amount of food required for a monster to reach level " + levelGoal + " is " + totalFood + " food.");
}

采纳答案by óscar López

You'll have to do this:

你必须这样做:

int levelMeal = (int) (5*(Math.pow(2,level-1)));
                  ^
           this is a cast

As you can see in the documentation, Math.pow()returns a doubleby design, but if you need an intthen an explicit cast must be performed.

正如您在文档中看到的那样,按设计Math.pow()返回 a double,但如果您需要 an,int则必须执行显式转换。

回答by niiraj874u

Math.pow return double and you assigning double value to int this is why it is giving error. You have to downcast it. Like

Math.pow 返回 double 并且您将 double 值分配给 int 这就是它给出错误的原因。你必须贬低它。喜欢

int levelMeal = (int)5*(Math.pow(2,level-1));

回答by DaoWen

I think there's typically hardware support on most modern processors for doing floating-point powers, but not integers. Because of that, for a generalpower, it's actually faster to do Math.powerwith a doubleand then convert it back to an int.

我认为大多数现代处理器通常都有硬件支持来执行浮点运算,但不是整数。正因为如此,对于一般电源,Math.power使用 adouble然后将其转换回a实际上更快int

However, in this case there's a faster way to do it for ints. Since you're doing a power of 2, you can just use the bitwise left-shift operatorinstead:

但是,在这种情况下,有一种更快的方法来处理整数。由于您正在执行 2 的幂,因此您可以改为使用按位左移运算符

int levelMeal = 5*(1<<(level-1));

As Rhymoid pointed out in his comment, that expression can be further simplified to remove the 1:

正如 Rhymoid 在他的评论中指出的那样,可以进一步简化该表达式以删除1

int levelMeal = 5<<(level-1);