C#Math计算的几个常用方法
1、返回绝对值
/// <summary>
/// 【1】返回绝对值(可扩展为绝对负数,只要前面加上负号)
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static string CalculateAVG(int num)
{
return Math.Abs(num).ToString();
}
2、返回输入数字的平方运算
/// <summary>
/// 【2】返回输入数字的平方运算(可扩展为立方或者其他自身运算)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double Square(double x) => x * x;
3、返回两个整数中间的倍数
/// <summary>
/// 【3】返回两个整数中间的倍数
/// </summary>
/// <param name="num"></param>
/// <param name="limit"></param>
/// <returns></returns>
public static List<int> FindMultiples(int num, int limit) => Enumerable.Range(1, limit / num).Select(x => x * num).ToList();
4、计算bool值的与、或和与或运算
/// <summary>
/// 【4】计算bool值的与、或和与或运算
/// </summary>
/// <param name="array"></param>
/// <param name="op"></param>
/// <returns></returns>
public static bool LogicalCalc(bool[] array, string op)
{
if (op == "AND")
return array.All(x => x);
else if (op == "OR")
return array.Any(x => x);
else
return array.Aggregate((i, j) => i ^ j);
}
5、求平均数(数组)
/// <summary>
/// 【5】求平均数(数组)
/// </summary>
/// <param name="marks"></param>
/// <returns></returns>
public static int GetAverage(int[] marks)
{
return (int)marks.Average();
}
6、计算数字是否满足特定条件
/// <summary>
/// 【6】计算数字是否满足特定条件:涉及(数字转字符串、字符串内元素数字运算、幂运算)
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static string DisariumNumber(int number)
{
return number.ToString().Select((x, i) => Math.Pow(char.GetNumericValue(x), ++i)).Sum() == number ? "Disarium !!" : "Not !!";
}
7、返回小数点后两位
/// <summary>
/// 【7】返回小数点后两位
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public static string FormatMoney(double amount)
{
return $"{"$"}{amount.ToString("0.00")}";
}
8、抽象类型转double类型(带null值判断)
/// <summary>
/// 【8】抽象类型转double类型(带null值判断)
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static double? ParseF(object s = null)
{
return double.TryParse(s?.ToString(), out var result) ? result : (double?)null;
}