【解決方法】与えられた問題の間違いを見つける


やあ、
私は最近インタビューを行い、以下のコードの間違いを見つけるために 1 つの質問をしました。

どなたか説明していただけると助かります…

C#
class Program
    {
        static void Main(string[] args)
        {
            int i = GetDecimalPlaces(0.001);
            Console.Write(i.ToString());
            Console.ReadLine();
        }

        public static int GetDecimalPlaces(double accuracy)
        {
            return Math.Min(0, -(int)(Math.Floor(Math.Log10(accuracy))));
            
        }
    }

「0.001」の答えは「3」でなければなりません。

ありがとう。

私が試したこと:

Log10についてはわかりません。

また、グーグルで検索しようとしましたが、結果はありません。

解決策 1

Logarithm10(x) は、底がこの場合 10 の場合、値 x を得るために必要な累乗を返します。
この場合、x は 0.001 なので、log10(0.001) は -3 を返します。つまり、10^(-3) = 0.001 です。
とにかく変えるだけ

Math.Min

Math.Max

解決策 3

The mistake in the code is with the Math.Min function in the GetDecimalPlaces method. The first argument of Math.Min should be the first number to compare, and the second argument should be the second number to compare. In this code, the arguments are swapped, which will cause the function to always return 0.

To fix this mistake, simply swap the two arguments in the Math.Min function, like this:

sql
Copy code
public static int GetDecimalPlaces(double accuracy)
{
    return Math.Max(0, -(int)(Math.Floor(Math.Log10(accuracy))));
}
This will ensure that the function returns the correct number of decimal places for the given accuracy.

解決策 2

デバッガーを使用して、コードが何を行っているかを確認します。 行を 1 行ずつ実行し、実行時に変数を調べることができます。

デバッガ – ウィキペディア (フリー百科事典)[^]
Visual Studio 2010 でのデバッグの習得 – 初心者向けガイド[^]

デバッガーは、コードが何をしているかを表示するためにここにあります。
デバッガーには魔法はありません。バグを見つけるのではなく、バグを見つけるのに役立つだけです。

コメント

タイトルとURLをコピーしました