C#。如何计算从输入中输入的数字?

C#. How to count digits entered from input?

这是一个数字相乘的代码,用户输入。

string x;
double t, s = 1;

Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();

结果显示在最后,但是如何让它显示输入的数字总数? 例如:我输入 1、2 和 3。所以总计数为 3。

string x;
double t, s = 1;
int count = 0;

Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
    count++;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count is: {0}", count);
Console.ReadLine();

为什么不是计数器的变量?

    Console.WriteLine("Enter some numbers: ");
    Console.WriteLine("To finish, press Enter");
    int i=0;
    while ((x = Console.ReadLine()) != "")
    {
        i++;
        t = Convert.ToDouble(x);
        s *= t;
    }
    Console.WriteLine("The result is: {0}", s);
    Console.ReadLine();

您必须计算使用计数器变量的循环迭代次数:

int loopCounter=0;
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
    loopCounter++;
}
Console.WriteLine("The count is: {0}", loopCounter);

您可以尝试计算字符串输入中的字符数 (x)。 int temp=x.Length();

  1. 最好用TryParse避免FormatException
  2. Char.IsDigit returns true 是当前字符是数字(显然)

示例:

string x;   
double t, s = 1;    
int digitCount = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    if (!Double.TryParse(x, out t))
        continue;
    foreach (var c in x)
        if (Char.IsDigit(c))
            digitCount++;
    s *= t;
}   
Console.WriteLine("The result is: {0}", s);  
Console.WriteLine("The count of digits is: {0}", digitCount);    
Console.ReadLine();