c#.如何计数从输入输入的数字
本文关键字:输入 数字 何计数 | 更新日期: 2023-09-27 18:12:16
这是一个乘数代码,用户输入。
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();
- 最好使用TryParse来避免
FormatException
- 字符。IsDigit返回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();
为什么不为counter设置一个变量呢?
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 ();