c#求绝对值

c#求绝对值
在C#中,可以使用以下不同的方法来求绝对值:

方法一:使用Math.Abs()函数

int num = -10;
int absValue = Math.Abs(num);
Console.WriteLine(absValue); // 输出:10
方法二:使用条件表达式

int num = -10;
int absValue = num < 0 ? -num : num;
Console.WriteLine(absValue); // 输出:10
方法三:使用位运算符(需要注意Int32.MinValue的情况)

int num = -10;
int absValue = (num ^ (num >> 31)) - (num >> 31);
Console.WriteLine(absValue); // 输出:10
这些方法都可以用来求一个数的绝对值,但是具体使用哪种方法取决于具体的需求和代码风格。

posted @ 2024-04-17 21:08  yinghualeihenmei  阅读(195)  评论(0编辑  收藏  举报