Reputation: 2668
How do you get a square root and an absolute value in Java?
Here is what I have:
if (variable < 0) {
variable = variable + variable2;
}
But is there an easier way to get the absolute value in Java?
variable = |variable|
Upvotes: 7
Views: 120760
Reputation: 1
int currentNum = 5;
double sqrRoot = 0.0;
int sqrRootInt = 0;
sqrRoot=Math.sqrt(currentNum);
sqrRootInt= (int)sqrRoot;
Upvotes: 0
Reputation: 1
import java.util.Scanner;
class my{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
double a,b,c=0,d;
d=1;
d=d/10;
int e,z=0;
System.out.print("Enter no:");
a=x.nextInt();
for(b=1;b<=a/2;b++)
{
if(b*b==a)
{
c=b;
break;
}
else
{
if(b*b>a)
break;
}
}
b--;
if(c==0)
{
for(e=1;e<=15;e++)
{
while(b*b<=a && z==0)
{
if(b*b==a){c=b;z=1;}
else
{
b=b+d; //*d==0.1 first time*//
if(b*b>=a){z=1;b=b-d;}
}
}
d=d/10;
z=0;
}
c=b;
}
System.out.println("Squre root="+c);
}
}
Upvotes: 0
Reputation: 178511
Use the java.lang.Math class, and specifically for absolute value and square root:, the abs()
and sqrt()
methods.
Upvotes: 1
Reputation: 5782
Try using Math.abs:
variableAbs = Math.abs(variable);
For square root use:
variableSqRt = Math.sqrt(variable);
Upvotes: 1
Reputation: 1503090
Use the static methods in the Math
class for both - there are no operators for this in the language:
double root = Math.sqrt(value);
double absolute = Math.abs(value);
(Likewise there's no operator for raising a value to a particular power - use Math.pow
for that.)
If you use these a lot, you might want to use static imports to make your code more readable:
import static java.lang.Math.sqrt;
import static java.lang.Math.abs;
...
double x = sqrt(abs(x) + abs(y));
instead of
double x = Math.sqrt(Math.abs(x) + Math.abs(y));
Upvotes: 25