0

我被一个模拟考试问题困住了。

我已经写了下面的课程并且它有效。但是,在powN方法的主体中,我需要使用for(){}循环。我还需要使用powN.

这是我的问题。如何使用 for 循环?什么是非防御方法以及如何使用它powN

public class Power {
    private double x = 0;

    Power(double x) {
        this.x = x;
    }

    public double getX() {
        return x;
    }

    public double powN(int n) {
        return Math.pow(getX(), n);
    }

    public static void main(String[] args) {
        Power p = new Power(5.0);
        double d = p.powN(2);
        System.out.println(d);
    }
}
4

3 回答 3

2

我的问题是如何使用 for 循环

我不熟悉java语法,但想法是:

public double powN(int n) {

    double tmp=1;
    for (int i=0;i<n;i++) {
        tmp=tmp*getX();
    }
    return tmp;
}

不知道非防御是什么意思

于 2012-08-11T20:01:05.057 回答
1

我已经从您的材料中阅读了有关防御性/非防御性方法的幻灯片。我猜你的教授希望你检查参数是否有效。像这样:

  public double powN(int n) {
    if (n < 0) {
      throw new UnsupportedOperationException("Only positive values are supported");
    }
    double tmp = 1;
    for (int i = 0; i < n; i++) {
      tmp = tmp * getX();
    }
    return tmp;
  }
于 2012-08-11T20:46:13.197 回答
1

非防御性只是意味着您没有专门编码来检查错误,例如如果 n == 0,则返回 0。

相反,您只需采用 n 的任何值并在 for 循环中使用它的值。

因此,不要使用内置的 Math 函数,只需编写一个 For 循环来做同样的事情。

double result = 0.0
for (int i = 0; i < n; i++) {
   result = result * x;
}
于 2012-08-11T20:04:42.697 回答