【发布时间】:2020-09-27 19:46:47
【问题描述】:
生成包含x 位数的最低和最高整数值的最佳方法是什么?
例如:
-
x= 1:最小值 = 0,最大值 = 9 -
x= 2:最小值 = 10,最大值 = 99 -
x= 3:最小值 = 100,最大值 = 999 -
x= 4:最小值 = 1000,最大值 = 9999
我觉得这应该是一件很容易完成的事情,但我很难理解它背后的数学原理。
这是我到目前为止生成 max 值 (based on this answer) 的结果:
public static int MaxIntWithXDigits(this int x)
{
if (x == 0) throw new ArgumentException(nameof(x), "An integer cannot contain zero digits.");
try
{
return Convert.ToInt32(Math.Pow(10, x) -1);
}
catch
{
throw new InvalidOperationException($"A number with {x} digits cannot be represented as an integer.");
}
}
如果有人可以帮助生成 min 值或建议对上述代码进行改进,我将不胜感激。
编辑
我快到了 - 这似乎适用于所有情况,除非x = 1(并且最小值预期为 0)
public static int MinIntWithXDigits(this int x)
{
if (x == 0) throw new ArgumentException(nameof(x), "An integer cannot contain zero digits.");
x -= 1;
try
{
return Convert.ToInt32(Math.Pow(10, x));
}
catch
{
throw new InvalidOperationException($"A number with {x} digits cannot be represented as an integer.");
}
}
【问题讨论】:
-
你的问题太宽泛了。您具体遇到了什么问题?您是否想到给定位数的 最小值 值与少一位加一位的 最大值 值相同?
-
它很笨,但它有效:
parseInt(x > 1 ? "1" + "0".repeat(x-1) : "0")
标签: c# math numbers number-formatting