使所有数字为负数
我有一些浮动:
-4.50
+6.25
-8.00
-1.75
我怎样才能将所有这些更改为负浮动,以便它们变成:
-4.50
-6.25
-8.00
-1.75
此外,我还需要一种方法来进行相反的操作,
如果浮动是负数,请将其设为正数。
I have a few floats:
-4.50
+6.25
-8.00
-1.75
How can I change all these to negative floats so they become:
-4.50
-6.25
-8.00
-1.75
Also I need a way to do the reverse
If the float is a negative, make it a positive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
一个简单的
或更好的解决方案,恕我直言:
正如@VegardLarsen 所发布的那样,
我建议避免 if/else (或等效的三元运算符),特别是如果您必须操作多个项目(在循环中或使用 lambda 函数 /em>),因为它会影响性能。
为了更改数字的符号,您可以简单地执行以下操作:
或者,当然,将其乘以 -1 :)
A trivial
or, the better solution, IMHO:
As @VegardLarsen has posted,
I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.
In order to change the sign of a number you can simply do:
or, multiply it by -1, of course :)
一些琐碎的事情怎么样:
反转:
<前><代码>$num = -$num;
仅将正数转换为负数:
仅将负数转换为正数:
How about something trivial like:
inverting:
converting only positive into negative:
converting only negative into positive:
重新编辑:“我还需要一种方法来进行相反的操作,如果浮动是负值,则将其设为正值”
将数字更改为其相反值。
re the edit: "Also i need a way to do the reverse If the float is a negative, make it a positive"
changes the number to its opposite.
我认为Gumbo的回答很好。有些人更喜欢这种奇特的表达方式,它可以做同样的事情:
编辑:显然您正在寻找一个可以使负数也变为正数的函数。我认为这些答案是最简单的:
I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:
EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:
使用alberT和丹涛解决方案:
从负到正,反之亦然
using alberT and Dan Tao solution:
negative to positive and viceversa
下面是一个简单的可重用代码,用于反转int、float、double 或decimal 的符号。
如果值为正,该方法将返回负值,反之亦然。
Here's a simple reusable code to inverse the sign of an
int, float, double or decimal
.If the value is positive, the method will return a negative value and vice versa.