繁体   English   中英

在 C# 中查找数字的位数

[英]Finding number of digits of a number in C#

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

    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);

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

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

使用char.IsDigit

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

有什么问题:

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

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

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

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 变量的 @ 是使其成为逐字变量(因为 base 是一个关键字)。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM