Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Trouble with Math Class  RSS feed

 
Kenneth Kim
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Supposing I assigned variables a,b, and c to the coefficients in the quadratic formula:

(-b +/- sqrt(b^2-4ac))/2a

How would I write that in Java? In my actual program I have assigned a as variable "coa", b as "cob", and c as "cob". Here is what I have tried without success:



When compiling, I get errors mainly saying that I cannot use a particular operator with a double variable.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Use "Math.sqrt()", not just "sqrt()".

2) Java doesn't have a built-in exponentiation operator -- you have to use the Math.pow() function.

Otherwise things are fine (assuming coa, cob, coc are of type "double".)
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For future reference, it will help a lot if you copy-and-paste the exact error message here. I would guess that the particular operator you are referring to is the ^. In Java, this is not an exponent operator as it is in other languages. As EFH says, you need to use Math.pow() instead. Notice that you need to specify the class name when you use a static method from another class (such as the Math class).

Layne
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!