简体   繁体   中英

Error when running Custom Square Root Function (Java)

So I created a method that I want to calculate the square root of any given integer. For an x such as 27, I would want it to display 3√3. Or for 28, 2√7, and so on. And I'll tell you in advance, I know there are other issues in this method-- I plan to address them.

public static void root(int x) {
    int [] a = new int [x]; //list of outside integers for each i
    int b = x; //inside
    int c = 1; //product of a[]
    double sqrt = Math.sqrt(x);

    if (sqrt != (int) sqrt) {
        for (int i=2; i < x; i++) {
        a[i] = 1;
        while (x%(i^2) ==0) { //ERROR HERE
            a[i] = a[i] * i;
            b = b/(a[i])^2;
        }
        c = c * a[i];
        }
        System.out.println(b+"\u221A" + c);
    }
    else {
        System.out.println((int) sqrt);
    }
}

Following execution for any integer that does not yield a clean root, I receive an error that says "/ zero". Above I have the lines marked where the error is said to have occurred. Thanks in advance!

The problem is this expression

x%(i^2)

The operator ^ is not exponentiation, it is bitwise XOR . On the first iteration i is 2 , and the result of 2 ^ 2 is ZERO. You are attempting to divide by zero (to get the remainder), which fails. Use

x%(i*i)

instead.

Throughout your answer, you use ^ to square numbers. However, this is actually a bitwise XOR operator. Instead, use Math.pow(numToSquare, 2) function, or simply multiply the number or expression by itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM