0

When I print the result of "chances" it keeps returning a value of "0". I am not sure if it has to do with me using the rand operator. How can I fix this so it will return its actual value instead of 0?

    p1Health = rand(50..100).to_i
    p1Attack = rand(25..50).to_i
    p1Overall = (p1Health + p1Attack).to_i

    p2Health = rand(50..100).to_i
    p2Attack = rand(25..50).to_i
    p2Overall = (p2Health + p2Attack).to_i

    p1p2 = p1Overall + p2Overall

    chances = p1Overall / (p1Overall + p2Overall)
Ryan
  • 151
  • 11
  • Remember in Ruby that capital letters have specific meaning, so variable and method names should be lower-case only. Consider using names like `p1_health` or, even better `player[0][:health]` by using proper data structures here. – tadman May 17 '18 at 18:35

3 Answers3

1

When calculating chances you're doing integer division, which will return a result rounded down to the nearest integer. In this case, you're seeing 0 because your result is meant to be a percentage (since it's less than 1, it rounds down to 0 in integer division).

To return the actual value you'll want to convert one of the integers to a Float, like so:

chances = p1Overall / (p1Overall + p2Overall).to_f

Hope this helps!

Zoran
  • 4,196
  • 2
  • 22
  • 33
  • That did it, thanks! – Ryan May 17 '18 at 18:47
  • 2
    There's also the little known / rarely used / often overlooked [`fdiv`](http://ruby-doc.org/core-2.5.1/Float.html#method-i-fdiv), e.g. `p1overall.fdiv(p1overall + p2overall)` – Stefan May 17 '18 at 18:55
1

In Ruby an integer divided by an integer yields an integer result. That is:

1 / 2
# => 0

Where 0 is the closest integer answer to that. What's different is:

5 / 2
# => 2

Where that's basically 2.5 rounded down to 2.

If you want a floating-point result:

chances = p1overall.to_f / (p1overall + p2overall)

Where that .to_f coverts to floating-point first. That yields a floating-point answer as a result.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

In Most language(c,c++, java,ruby, python ..etc) integer/integer yields integer result. you have to use at least one value to be the float.

that's the basic convention used by many languages:

The operation performs on:

integer + integer => integer
integer - integer => integer
integer / integer => integer
integer * integer => integer  
float + integer => float
integer + float => float
float / integer => float
integer / float => float
rahul mishra
  • 1,390
  • 9
  • 16