簡體   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