-1

I have been working on a short project the last two days, but now everything falls apart, because there is one equation which returns 8.660254 when calculated in a C++/C# program but 0 when you try to calculate it by hand or with a calculator.

Equation:

float mgr1 = (x + tr * 0.5f - tr / 2) * 1.73205f * 10.0f;

In my case:

x = 0;
tr = 1;
float mgr1 = (0 + 1 * 0.5f - 1 / 2) * 1.73205f * 10.0f;

The right result is 0 but when calculated in C++, like this, it returns 8.660254? Am I getting crazy? Is there something about C++ which I do not know? What is it?

enter image description here

enter image description here

GSerg
  • 76,472
  • 17
  • 159
  • 346
Landon
  • 13
  • 1
  • 6
    Integer division on 1/2 gives you 0. Change that to 1.0/2 and you will get the result you expected ... *approximately* correct. – Ian Apr 23 '16 at 15:58

1 Answers1

5

The / operator for integers returns a integer, not a floating-point value. 1/2 is 0.

1.0/2 or 1/2.0 return what you expect.