Soldato
- Joined
- 24 Apr 2011
- Posts
- 5,455
So at school, I started learning Java, and I have to do this program. Here is the question.
I managed to do it all, without getting any errors, but the answers are wrong
If you put a=1, b=2 and c=1, you should get Root 1 = -1 and root 2 = -1 aswell yet my answers are -2 and -2.
This is what I did till now.
I am pretty sure the problem is here
Reason is, if I remove the 2 2, and put it as (Math.pow(temp , 0.5))/(a) i get -2 still, o that makes me think it is not reading the 2, or just ignores it. I tried it out with the calculator, and if you do /1, the roots ome -2 and -2.
Please tell me, what am I doing wrong :S
P.S. I'm new, so don't be too harsh. I might have not even identified the mistake place.
In the main method of a class Roots.java find the roots of the equation ax2+bx+c=0 such that
If a=0 and b=0 print a message that the equation is degenerate.
If a=0 and b<>0 there exists one root –c/b
If a<>0 and c=0 there exists two roots –b/a and 0
If b2-4ac < 0 there exist two complex roots
Else Use formula
I managed to do it all, without getting any errors, but the answers are wrong

If you put a=1, b=2 and c=1, you should get Root 1 = -1 and root 2 = -1 aswell yet my answers are -2 and -2.
This is what I did till now.
import java.util.*;
public class Question4
{
public static void main (String args []){
int a, b, c;
double temp, root1, root2;
Scanner s=new Scanner (System.in);
System.out.println ("Enter coefficient of x^2");
a = s.nextInt();
System.out.println ("Enter coefficient of x");
b = s.nextInt();
System.out.println ("Enter constant");
c = s.nextInt();
temp = ((b*b)-(4*(a)*(c)));
if (a==0 & b==0 )
System.out.println("Equation is degenerate");
else if (a==0 & b!=0)
System.out.println("there exists one root" + (-c/b));
else if (a!=0 & c==0)
System.out.println("There exists two roots" + (-b/a) + ("0"));
else if (temp < 0)
System.out.println ("There exists two complex roots");
else {
root1 = (-b + (Math.pow(temp , 0.5))/(2*a));
root2 = (-b - (Math.pow(temp , 0.5))/(2*a));
System.out.println ("Root 1 is " + root1);
System.out.println ("Root 2 is " + root2);
}
}
}
I am pretty sure the problem is here
else {
root1 = (-b + (Math.pow(temp , 0.5))/(2*a));
root2 = (-b - (Math.pow(temp , 0.5))/(2*a));
Reason is, if I remove the 2 2, and put it as (Math.pow(temp , 0.5))/(a) i get -2 still, o that makes me think it is not reading the 2, or just ignores it. I tried it out with the calculator, and if you do /1, the roots ome -2 and -2.
Please tell me, what am I doing wrong :S
P.S. I'm new, so don't be too harsh. I might have not even identified the mistake place.