1

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

INGUES
  • 25
  • 1
  • 5

3 Answers3

5

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

Chris Nash
  • 2,941
  • 19
  • 22
0

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));
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Your solution can create a DivideByZero exception if the denom is 0 – Eric B. Jan 26 '12 at 22:42
  • @EricB. - I restored to the previous version that used multiplication. I assume the OP checks `denom` somewhere earlier. – Tomasz Nurkiewicz Jan 26 '12 at 22:46
  • Of course, you have the opposite problem now (although unlikely) that you can go beyond the bounds of max-int or max-long. Although, a quick test shows that it doesn't generate an error - Long.MAX_VALUE ^ 2 = 1. I don't know if the resultant sign would still necessarily be accurate, however. I do agree that the best option is to just check that `denom != 0` prior. – Eric B. Jan 26 '12 at 22:56
  • The problem with this is that `32768 * 65536 < 0` Its better to do two checks for sign. `(num >= 0) == (denum >= 0) ? "" : "-"` – Peter Lawrey Jan 27 '12 at 08:36
0

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
Patrick87
  • 27,682
  • 3
  • 38
  • 73