我有一个for循环,如:
for (int indexCount = 2, thirdNumber.ToString().Length!=1000; indexCount++)当thirdNumber中有1000位数字时,我希望循环终止。我该怎么做?
发布于 2017-07-15 16:31:36
有1000位数字的int是不可能的。最大int值为2,147,483,647,只有10位数。据我所知,没有任何内置数据类型可以表示1000位数的数字,甚至是100位数。
编辑:A BigInteger可以容纳任意大的数字(谢谢布拉德利·乌夫纳)。您需要添加对System.Numerics程序集的引用。如果您使用/正在使用它作为您的数据类型,那么您最初对thirdNumber.ToString()!=1000的比较将是一个有效的检查,以确定它是否为1000位数字。
您还可以采取一种更基于数字的方法,并将正在检查的BigInteger与最小的1000位数字进行比较,即1后面是999个零。我不确定用这个大小的数字哪种方法会更快,虽然我怀疑两个BigIntegers之间的比较。
class Program
{
static void Main(string[] args)
{
BigInteger minThousandDigits = BigInteger.Parse(new string('9', 999)) + 1;
BigInteger thousandMoreDigits = BigInteger.Parse(new string('5', 1000));
BigInteger notAThousandDigits = BigInteger.Parse(new string('9', 999));
//Displays false
Console.WriteLine($"Is the first number less than a thousand digits? {thousandMoreDigits < minThousandDigits}");
//Displays true
Console.WriteLine($"Is the second number less than a thousand digits? {notAThousandDigits < minThousandDigits}");
Console.ReadLine();
}
}发布于 2017-07-15 16:41:00
使用do循环:
int indexCount = 2;
do
{
// Whatever
indexCount++;
} while (thirdNumber.ToString().Length != 1000);注意,在上面的示例中,循环总是至少执行一次。您可以通过使用break语句来避免这种情况:
int indexCount = 2;
do
{
if (thirdNumber.ToString().Length == 1000) break;
// Whatever
indexCount++;
} while (true);以上假设长度最终将等于1000,否则就会有一个无限循环。
https://stackoverflow.com/questions/45120338
复制相似问题