[英]How can i count how many zeros will there be in the answer to an equation and said number that is followed by the zeros
double numone = Console.ReadLine();
double numtwo = Console.ReadLine();
double answer = numtwo * numone;
Console.WriteLine($"{numone} multiplied by {numtwo} is {answer}");
现在让我们假设 numone 是 30 万亿,numtwo 是 30 亿,答案将是 9+E22,但我也想在之后说“那是 (Number) 后跟 (NumOfZeros) 零”? 我怎样才能让它自动检索后面的零的数量和数量,然后打印它们,现在看到我只想计算数字后面的零,所以假设数字是 90900,我希望它说 2 个零。 不是 3. 我对如何使其计数为零有一个模糊的想法,但没有一个想法如何仅计算数字后面的零和零之后的数字。 如果它在 0 之后看到一个非零数字,基本上让它将 NumOfZeros 重置为 0,并且让它也获得它没有重置的第一个 0 之前的数字。
您可以使用string.LastIndexOfAny()
。
首先,声明一个char
数组,其中包含除零以外的所有数字。 当然,这是假设用户输入是严格的数字。 否则,您将需要事先进行更多错误检查。
var nonZero = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
var strNum = "90900";
// Gets the index of the last non-zero number
var lastNumIndex = strNum.LastIndexOfAny(nonZero);
if (lastNumIndex < strNum.Length - 1)
{
// If there are zeros after that last non-zero
var numZeros = strNum.Length - 1 - lastNumIndex;
Console.WriteLine("Zeros: {0}", numZeros);
}
else
{
// There are no trailing zeroes
Console.WriteLine("No trailing zeroes");
}
不同的方法
var strNum = "90900";
var count = 0;
foreach (var num in strNum)
{
count++;
if (!Equals(num, '0'))
{
count = 0;
}
}
Console.WriteLine(count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.