编写计算指数的程序

时间:2012-10-30 07:43:38

标签: java math

我正在尝试编写一个打印数字2的指数结果的程序,我想打印出10次。我想创建一个使用Math.pow(x,y)方法计算指数值的方法。

2到0 = 1的幂 2到1 = 2的功率 2到2 = 4的力量

我有几个问题。你能像我在下面那样在for循环中使用Math.pow方法吗?如何在for循环中的Math.pow(x,y)方法中声明x和y的值,还是必须在for循环之外进行?另外,在Eclipse中的raiseIntPower方法中,当我使用int n作为参数时,它给出了“重复的局部变量错误”。我的理解是方法参数指定方法所需的参数。我不明白那个重复错误的含义。

import acm.program.*;


public class Exponents extends ConsoleProgram {

  public void run(){
      for (int n = 0; n <= 10; n++) {

            println("2 to the power of " + n + " = " + raiseIntPower(n)); 

     } 

  }
private int raiseIntPower (int n){
   int total = 0;
   for( int n = 0; n <= 10; n++){
     total = Math.pow(2, n);

  } 

return total; 
  }
}

4 个答案:

答案 0 :(得分:7)

我不明白你想做什么

只需替换声明

println("2 to the power of " + n + " = " + raiseIntPower(n)); 

println("2 to the power of " + n + " = " + Math.pow(2,n)); 

它应该这样做,不需要raiseIntPower()

我认为您对Math.pow()的使用感到困惑,请参阅此处以澄清Math.pow()

答案 1 :(得分:1)

Math#pow(double a, double b)其中a是基数,b是指数ab,它返回double,因此如果要丢弃精度,则必须格式化返回值。

你可以删除raiseIntPower方法。

for (int n = 0; n <= 10; n++) {
     println("2 to the power of " + n + " = " + Math.pow(2,n)); 
} 

答案 2 :(得分:0)

检查一下

import acm.program.*;

public class Exponents extends ConsoleProgram {

  public void run(){
      for (int n = 0; n <= 10; n++) {

            println("2 to the power of " + n + " = " + raiseIntPower(n)); 

     } 

  }
private int raiseIntPower (int n){
   int total = 0;   
   total = (int)Math.pow(2, n);

   return total; 
  }
}

答案 3 :(得分:0)

Eclipse为您提供了“重复的局部变量错误”,因为存在重复的变量。

private int raiseIntPower (int n){
    int total = 0;
    for( int n = 0; n <= 10; n++){
        total = Math.pow(2, n);
    } 
    return total; 
}

您为输入声明了变量n。在for循环中,您声明了另一个变量n。 {for循环中的int n及其引用应更改为其他名称,例如int i

相关问题