简体   繁体   English

Java:使用Math.abs并记下以后使用的频率

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

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. 如果用户输入一个分子和一个分母,并将它们都设为负数,则无法显示-1 / -2。 Same with only one negative, I cannot show 1/-2. 与一个负数相同,我不能显示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. 我想出的解决方案是通过使用Math.abs从num和den中除去负数,然后在输出中添加负数,前提是Math.abs仅需使用一次。 If it was utilized twice I will include logic to only output the num and den with the negative removed. 如果使用两次,我将包括仅输出num和den并删除负数的逻辑。 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. 当用户输入num或den或两者的正数时,如何保持Math.abs的使用频率计数并防止出现误报。

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. *其中num是用户输入的数字,snum是abs转换的数字。

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks, INGUES 谢谢,INGUES

如果分母为负,只需翻转两个符号。

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));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM