1

Pythonで数値のn乗根を見つける次の関数を作成しました。

def find_root(base, nth_root, top = None, bottom = 0):
    if top == None: top = base

    half = (float(top) + float(bottom)) / 2.0 

    if half**nth_root == base or half == top or half == bottom:
        return half
    if half**nth_root > base:
        return find_root(base, nthRoot, half, bottom)
    if half**nth_root < base:
        return find_root(base, nthRoot, top, half)

おそらくお分かりのように、デフォルトのパラメータに大きく依存しています。(1)これを行うためのより良い方法(再帰的にしたい)、および(2)(この質問はおそらく1と同じ答えを持っています)言語がデフォルトのパラメーターをサポートしていない場合、Javaでこれを行うにはどうすればよいですか? ?

私はJavaを初めて使用し、違いを理解しようとしています。

ありがとう、

マイケルG。

4

2 に答える 2

4

メソッドのオーバーロードを使用して、デフォルトのパラメーターをシミュレートできます。

int find_root(int base, int nth_root) {
  return find_root(base, nth_root, -1, 0);
}

int find_root(int base, nth_root, int top, int bottom) {
    // ...
}
于 2012-08-14T14:05:50.253 に答える
0

varargs機能を使用することもできます。ここの例。

于 2012-08-14T14:15:50.797 に答える