Math.Pow weird problem [C#]

Updated on May 2, 2017 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on April 24, 2017

Hello everybody,

this is the first time posting here, since it is the first time I couldn’t find an answer to a question using Google.
A little context to what I am doing: I wanted to learn C# took up Brackey’s course on Youtube and since I already learned C I wanted to take his Calculator example a little further. I included the ability to add, subtract, multiply and divide by using a switch and asking for an operator. Now I also wanted to include square root of a number and the square of a number. So I used the Math.Pow(double, double) function to include it.

Now this is my code for it:

case "root":
     num03 = Math.Pow (num01, 1/2);
     break;
case "square":
    num03 = Math.Pow (num01, 2);
    break;
 

Edit: I had to change the code example to not use colours since it was showing the html code. Might have something to do with me using mono on an ubuntu.
Edit 2: Ok, still doing it for me. If there is a problem with being able to read the code, let me know or if it is just my pc.

Now here is the weird part:
After bug testing with the number 9 (I also included a few debug “Console.WriteLine(string);” in the earlier code to make sure that it didn’t have anything to do with the variable being saved wrongly), I got 1 as the solution for the “root” case and 81 for the “square” case.
Last time I checked the square root of 9 is 3. Where does this problem come from?

Note: For further bug testing I used “Math.Sqrt(double)” instead of “Math.Pow(double, double)” and the solution was 3. So while I can get the program to function I am still curious to what is the reason for such a math error.

Thank you for reading
InSicK.

  • Liked by
Reply
1 on April 24, 2017

You will need to fix the code snippet.

Helpful
on April 24, 2017

Should be fixed now.

Show more replies
  • Liked by
Reply
Cancel
0 on May 2, 2017

So I found out what the problem was:

it is pretty simple.

//wrong way:
case "root":     
     num03 = Math.Pow (num01, 1/2); //1 and 2 are seen as integers.
     break;
//right way:
case "root":
     num03 = Math.Pow (num01, 1.0f/2.0f  //1 and 2 are seen as floats
     break;

In the wrong example the Compiler divides an integer of 1 by an integer of 2 and gives you an integer because you have been working with integers. Since that integer would be 0.5 it is rounded to 0. For this reason it will always give 1, it doesn’t matter what number you type in.
In the right example the Compiler divides a float of 1 by a float of 2 and gives you a float because you have been working with floats. This float is 0.5, so it works.

I hope someone who runs into the same problem finds this post.

  • Liked by
Reply
Cancel