Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top