简体   繁体   中英

Use Math.Pow and keep the sign?

Is there anyway I can do this without using ifs?

Like I want to do Math.Pow(-5f,2f) to come out as -25 not 25?

How about with Math.Sign :

Returns a value indicating the sign of a single-precision floating-point number.

So the computation would be:

Math.Sign(x) * Math.Pow(x, y)

If the idea is to always use the sign of the first operand even when the Pow operation returns a negative value (instead of just negating the result when the first operand is negative), you can do:

Math.Sign(x) * Math.Abs(Math.Pow(x, y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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