1

I am really confused why this is happening, my code:

double x = Math.Sqrt(2/3);
MessageBox.Show(x.ToString());

Displays 0. The answer is

0.8164, I know I will also have to use Math.Round to round this up, but for the moment the issue is I'm getting 0

JohnChris
  • 1,360
  • 15
  • 29
  • 2
    `2/3` is an integer division and returns `0 `. You wantto use floating point numbers – UnholySheep Dec 01 '16 at 09:11
  • 1
    Why is this being downvoted? This question is well-written, with expected and actual behaviour documented. – Bathsheba Dec 01 '16 at 09:14
  • 1
    @Bathsheba - Because it doesn't show any research effort. Even an attempt at diagnosing the issue would show that the part of the code producing the problem is the division and not the square root operation. – Sayse Dec 01 '16 at 09:15
  • 2
    We can agree to disagree. Something like this is difficult for a beginner to research. – Bathsheba Dec 01 '16 at 09:16
  • @Sayse, I inserted a breakpoint and tried to find the issue, my output window just showed zero, I do need to increase my debugging skills, and just for your information I did look for previous similar posts, I just didn't word my question the correct way – JohnChris Dec 01 '16 at 09:17
  • @JohnChris - I didn't say you didn't research, just that you didn't show your research. Explaining that you either did find that 2/3 produced 0 instead of a float number but not sure why or that you searched for "Math.Sqrt incorrect result" or similar would probably be enough to avoid downvotes – Sayse Dec 01 '16 at 09:21
  • 1
    fair enough... learned a couple things here within 5 min, thanks:p – JohnChris Dec 01 '16 at 09:24

2 Answers2

10

The problem is caused by automatic integer evaluation of the numbers. Use:

double x = Math.Sqrt(2f/3f);
MessageBox.Show(x.ToString());
Emad
  • 3,809
  • 3
  • 32
  • 44
2

2 / 3 is an integer operation, what you want is 2.0 / 3 which means I want to use floating point numbers.

What you consider an Intereger is different from what you know from Maths. In programming languages it means that a result of an int-operation is allways an integer in itself.

In your example 2 / 3 is an integer-operation which means the result is rounded down to the nearest integer, which is zero. To avoid this indicate that at least one of your operands should be treates as some floating-point value, either using 2.0 or 2f (alternativly 3.0 or 3f).

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111