查找C#中数字的位数

时间:2014-12-14 16:51:37

标签: c# numbers digits

我试图在C#中编写一段代码来查找整数的数字位数,该代码适用于所有数字(负数和正数),但我有10,100,1000和等等,它显示的数字比数字少一个数字。实际位数。比如10比1和100转2 ..

    long i = 0;
    double n;
    Console.Write("N? ");
    n = Convert.ToInt64(Console.ReadLine());

    do
    {
        n = n / 10;
        i++;
    }
    while(Math.Abs(n) > 1);
    Console.WriteLine(i);

6 个答案:

答案 0 :(得分:6)

你的状态是Math.Abs(n) > 1,但是在10的情况下,你第一次只有大于1。您可以将此检查更改为>=1,这应该可以解决您的问题。

do
{
    n = n / 10;
    i++;
}
while(Math.Abs(n) >= 1);

答案 1 :(得分:4)

使用char.IsDigit

string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);

答案 2 :(得分:2)

出了什么问题:

Math.Abs(n).ToString(NumberFormatInfo.InvariantInfo).Length;

实际上,将数字转换为字符串与某些算法相比在计算上是昂贵的,但是很难处理负数,溢出,...

您需要使用Math.Abs来确保标记不计算,并且使用NumberFormatInfo.InvariantInfo是安全的选项,以便某些使用空格和重音的文化不会改变行为。

答案 3 :(得分:1)

public static int NumDigits(int value, double @base)
{
    if(@base == 1 || @base <= 0 || value == 0)
    {
        throw new Exception();
    }
    double rawlog = Math.Log(Math.Abs(value), @base);
    return rawlog - (rawlog % 1);
}

此NumDigits函数用于查找任何基数中值的位数。它还包括无效输入的错误处理。带有基本变量的@是使它成为一个逐字变量(因为base是一个关键字)。

答案 4 :(得分:0)

Console.ReadLine().Replace(",", String.Empty).Length;

答案 5 :(得分:0)

这会计算字符串中的所有字符

        int amount = 0;
        string input = Console.ReadLine();
        char[] chars = input.ToArray();

        foreach (char c in chars)
        {
            amount++; 
        }
        Console.WriteLine(amount.ToString());
        Console.ReadKey();
相关问题