Click here to Skip to main content
16,016,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have recently given an interview, where they asked one question to find the mistake in below code.

It would be helpful if anyone can describe...

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


answer should be "3" for "0.001".

Thank You.

What I have tried:

I have no idea about Log10.

Also I tried to google but there is no result.
Posted
Updated 18-Mar-23 11:28am
Comments
CodeReady 30-Dec-16 0:55am    
Why don't you try to debug this, you won't need google for that.

Logarithm10(x) will return the power that a base in this case 10, must raise in order to get the value x,
in this case, the x is 0.001, so log10(0.001) return -3, i.e. 10^(-3) = 0.001
Anyway, just change
Math.Min

to
Math.Max
 
Share this answer
 
v2
Comments
Jagadeesh Bollabathini 30-Dec-16 3:30am    
Yes.
It returns the answer as expected.
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.
 
Share this answer
 
Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing.
There is no magic in the debugger, it don't find bugs, it just help you to.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900