Java: Use Math.abs and keep a count of how often it was used for later use

1.1k views Asked by At

I'm trying to write a program that modifies fractions and I need to make sure that the "-" negative is properly outputted only once. If the user inputs a numerator and a denominator and puts them both in as a negative I cannot show -1/-2. Same with only one negative, I cannot show 1/-2. The solution that I've come up with is to remove the negatives from both the num and den by using Math.abs and then add the negative during the output IF Math.abs only had to be utilized once. If it was utilized twice I will include logic to only output the num and den with the negative removed. How do I keep a count of how often the Math.abs was utilized and also prevent having a false positive show up when the user enters a positive number for either the num or den or both.

My code at the moment only does the work of converting to an absolute value so I have nothing to show for keeping a count.

snum = Math.abs(num);

*Where num is the user inputted number and snum is the abs converted number.

Any help would be appreciated.

Thanks, INGUES

3

There are 3 answers

0
Patrick87 On BEST ANSWER

Pseudocode:

if numerator < 0 and denominator < 0 then
   numerator = -numerator
   denominator = -denominator
   sign = '+'
elsif numerator < 0 then
   numerator = -numerator
   sign = '-'
elsif denominator < 0 then
   denominator = -denominator
   sign = '-'
end if

print sign, numerator, '/', denominator
4
Tomasz Nurkiewicz On

No, leave minus sign in the internal representation intact, it is only the output that gets corrupted. Here is my solution:

String sign = (num * denom < 0)? "-" : "";
System.out.println(sign + Math.abs(num) + "/" + Math.abs(denom));
1
Chris Nash On

If the denominator is negative, just flip the signs of both.