How can I find the absolute value of the difference of two numbers. (BEGINNER)
ie My program will compute |ab| (in that order), WITHOUT using math.abs.
This is what I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double b = in.nextDouble();
double value = a - b;
System.out.println("Enter a: ");
a = in.nextDouble();
System.out.println("Enter b: ");
b = in.nextDouble();
//If value is negative...make it a positive number.
value = (value < 0) ? -value : value;
System.out.println(a + "-" + b + "=" + (a - b));
System.out.println(b + "-" + a + "=" + (b - a));
}
}
PLEASE HELP, I AM A BEGINNER!
A bit more formatted code.
import java.util.Scanner;
class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a;
double b;
System.out.println("Enter a: ");
a = in.nextDouble();
System.out.println("Enter b: ");
b = in.nextDouble();
double value = a - b;
//If value is negative...make it a positive number.
value = (value < 0) ? -value : value;
System.out.println("|"+a + "-" + b +"|" + " =" + value); // value should be printed here instead of (a-b) or (b-a)
System.out.println("|"+b + "-" + a +"|" + " =" + value);
}
}
First of all you are taking scanner two times without any reason
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
double a = in.nextDouble();
System.out.println("Enter b: ");
double b = in.nextDouble();
double value = a - b;
double value2 = b - a;
//If value is negative...make it a positive number.
value = (value < 0) ? -value : value;
value2 = (value2 < 0) ? -value2 : value2;
System.out.println(a + "-" + b + "=" + value); //chaged to value
System.out.println(b + "-" + a + "=" + value2); //changed to value
}
its simple
assume we have two int a and b. And a variable diff to find the absolute difference. code:
int diff=a-b;
if(diff<0)
diff=b-a;
here you will get the absolute value between a and b.
To have an absolute value for your
value
You can add if condition like below
if (value < 0) {
value = value * -1;
}
So that the negative answer (difference) will always be converted to positive (absolute) value.
If the value is greater than 0, then no need as it is already a positive number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.