-4

The following code produces result zero:

double x = 1/2 + Math.Tan(0) + 1/2;

Or any other code that involves Math.Tan and some other items in the expression. Compiler seems to just calculate the Tan value and ignore the rest of the expression. Why is that?

A6EE
  • 141
  • 1
  • 8
  • 1
    Because of floating point math. `1/2` is *not* `0.5`. I'll look for a dupe target to explain this... – nvoigt Jun 25 '18 at 14:21
  • Maybe because of `1/2` is integer division, thus the result is 0. – Nikolay K Jun 25 '18 at 14:21
  • @nvoigt `1/2` in C# has nothing to do with floating point. – user202729 Jun 25 '18 at 14:21
  • 2
    for a quick and dirty way just do `1/2.0` – slow Jun 25 '18 at 14:22
  • 1
    Keep in mind that `Math.Tan` has been used in thousands of applications and called millions (billions?) of times. It's unlikely you're just now discovering a bug in such a critical piece of code. When dealing with battle-tested code like this, your first question should be "what am I doing wrong". – mason Jun 25 '18 at 14:22

2 Answers2

1

Break it down into pieces and keep in mind that integer division will result in an integer with the fractional component truncated off of the result.

double x = 1/2 + Math.Tan(0) + 1/2;

double x = (1/2) + Math.Tan(0) + (1/2);

double x = (0) + 0 + (0);

double x = 0;
Igor
  • 60,821
  • 10
  • 100
  • 175
1

The expression 1/2 evaluates to 0, because both operands are integers and thus the division is integer division, rounded down to the nearest integer. So 1/2 + Math.Tan(0) + 1/2 is equivalent to 0 + 0 + 0.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34