#11624: 為什麼答案總是跑出1跟-4,無法跑出題目所要的2跟-5?


smallgirl520 (haha)


請問有人知道為何我這裡兩個實根無法印出2跟-5嗎?

 

import java.util.Scanner;


public class A006 {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int judge = (b ^ 2) - (4 * a * c);

int root1 = (int) (-b + Math.sqrt(judge)) / (2 * a); //1
int root2 = (int) (-b - Math.sqrt(judge)) / (2 * a); //-4

if (judge > 0) {
System.out.println("Two different roots x1=" + root1 + " , x2=" + root2);
} else if (judge == 0) { // root1=root2=0,印其中一根即可
System.out.println("Two same roots x=" + root1);
} else {
System.out.println("No real root");
}

}

}

}

 

#11627: Re:為什麼答案總是跑出1跟-4,無法跑出題目所要的2跟-5?


smallgirl520 (haha)


 

請問有人知道為何我這裡兩個實根無法印出2跟-5嗎?

 

import java.util.Scanner;


public class A006 {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int judge = (b ^ 2) - (4 * a * c);

int root1 = (int) (-b + Math.sqrt(judge)) / (2 * a); //1
int root2 = (int) (-b - Math.sqrt(judge)) / (2 * a); //-4

if (judge > 0) {
System.out.println("Two different roots x1=" + root1 + " , x2=" + root2);
} else if (judge == 0) { // root1=root2=0,印其中一根即可
System.out.println("Two same roots x=" + root1);
} else {
System.out.println("No real root");
}

}

}

}

 

我知道問題出在哪了

在judge運算式那的b^2改成b*b就可以了~~~