1

I'm missing something obvious i guess. Or have some stupid mistake in my head, but anyway I can't figure it out.

My code is this.

for (int i = 0; i < ringNumber; i++)
{
    float x = (radius * ringNumber) - (i * radius);
    float y = (-1/2 * radius * ringNumber) - (i * 1/2 * radius);
    Debug.Log ("Radius: " + radius + ", Ringnumber : " + ringNumber + ", i : " + i);
    Debug.Log ("In Loop 3 Vertical : " + x + "  " + y);
}

what I get is

enter image description here

For Radius = 2 and Ringnumber = 2, Y is given out as 0 both times. In my mind it should be -2 and -3. Why isn't it?

I have similar mistakes in other loos like this, but some work out just fine.
Its not that difficult math I thought -2*2/2 minus zero times something. Should be -2 or not?

m7913d
  • 10,244
  • 7
  • 28
  • 56
Soronume
  • 23
  • 2
  • 5
    Standard bug, 1/2 always produces 0. You need 1/2f to get a floating point division. – Hans Passant May 14 '17 at 13:31
  • Or use `radius/2` or use `0.5*radius`. – Lutz Lehmann May 14 '17 at 15:55
  • Possible duplicate of [Why does integer division in C# return an integer and not a float?](https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float) – Ruzihm May 17 '19 at 22:01

1 Answers1

4

This is the point:

1.0/2.0 = 0.5 and 1/2 = 0

When dividing integer values the result would be an integer too. So 1/2 would round to zero. Use 1.0/2.0

for (int i = 0; i < ringNumber; i++)
{
        float x = (radius * ringNumber) - (i * radius);
        float y = (-1.0/2.0 * radius * ringNumber) - (i * 1.0/2.0 * radius);
        Debug.Log ("Radius: " + radius + ", Ringnumber : " + ringNumber + ", i : " + i);
        Debug.Log ("In Loop 3 Vertical : " + x + "  " + y);
}

As a best practice always use numeric values with like this: #.0 this prevent such errors. Also you can try this alternative. more suffix

1d/2d = 0.5

This way you explicitly say that those values are double and are not integers. So the resulting value will also be double too.

Community
  • 1
  • 1
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116