Reputation: 19
So I'm currently programming a method/class in java whereby I find the roots of a quadratic equation given a, b, c. I declared the variables a, b, and c as doubles. Here's some of my code:
discriminant = Math.pow(b,2) - 4*a*c, 0.5;
System.out.println("Discriminant is " + discriminant);
System.out.println("numerator is " + -b + Math.pow(discriminant,0.5));
System.out.println("square root of discriminant is " + Math.sqrt(discriminant));
So an example I used was a = 5, b, = 6, and c = 1. I got the wrong roots and so tried to debug it via the print statements above. Every time I add -b and Math.pow(discriminant, 0.5) together (for the first root) I get a very strange number. I should be getting -6 + 4 = -2 but instead it prints -6.04.0.
Surely this must be an amateur mistake but I can't seem to find a similar error online anywhere. Why are there two decimal points? Are you not suppose to add doubles like that?
Thank you so much in advance for any input y'all may have about this.
Upvotes: 1
Views: 80
Reputation: 5175
This instruction:
System.out.println("numerator is " + -b + Math.pow(discriminant,0.5));
is just converting the numbers into String
s and then performing string concatenation.
Try:
System.out.println("numerator is " + (-b + Math.pow(discriminant,0.5)));
Upvotes: 5