1

I built the following function that finds the nth root of a number in Python:

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)

As you can probably tell it is highly dependent upon default parameters. Is there (1) a better way to do this (I want it to be recursive), and (2) (this question probably has the same answer as 1) how can I do this in Java if the language does not support default parameters?

I'm new to Java and trying to work out the differences.

Thanks,

Michael 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

您还可以使用可变参数功能。这里的例子。

于 2012-08-14T14:15:50.797 回答