Sunday, August 12, 2012

Simple Flip-a-coin Application

As I was playing around, I made a simple, and I mean SIMPLE Flip-a-coin application.
Here is the code:

puts "You are flipping a coin"
if rand.round == 0
  coin = "heads"
else
  coin = "tails"
end
puts "It is " + coin
Let me explain it a bit.
'puts' just prints out a string (string is basically a word or a sentence). One important thing to note is that 'puts' also goes to a new line after the string has been printed out. If you want to continue printing strings in the same line, use 'print' instead of 'puts'. To go to a new line with 'print' just add the newline character '\n'.
Alright, so we're printing out 'You are flipping a coin'.
We then say "if a random number between 0 and 1 (that is what 'rand' does, it gives you a random number between 0 and 1) that is rounded to the nearest integer (that is what 'round' does) is zero, create a new variable called 'coin' and make it a string, that says 'heads'. If it is not 0 then make a new variable called coin and make it's value a string 'tails'." We then end the 'if statement' with the word 'end'. One thing to note here again is that 'rand' will give you a decimal number, such as 0.8713584669602163 and this is why we have to round it either up (if it's more than 0.5) or down (if it's less than 0.5).
We then print the line "It is " and add the coin variable which has either the value 'heads' or 'tails'.
Like I said, very simple.
Here is the output:

No comments:

Post a Comment