Created
August 11, 2019 00:51
-
-
Save vlad-bezden/2f3a1b444f4de07ee6120c717efef373 to your computer and use it in GitHub Desktop.
Exercise #6 from "Get Programming with Go" book by by Nathan Youngman and Roger Peppé
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a program that randomly places nickels ($0.05), dimes ($0.10), | |
and quarters ($0.25) into an empty piggy bank until it contains at least $20.00. | |
Display the running balance of the piggy bank after each deposit, | |
formatting it with an appropriate width and precision. | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
const ( | |
bankThreshold = 20.0 | |
) | |
var coinsValue = [...]float64{0.05, 0.1, 0.25} | |
// coin generates random coin from coinsValues | |
func coin() float64 { | |
return coinsValue[rand.Intn(len(coinsValue))] | |
} | |
func main() { | |
// set random numbers, otherwise it will produce the same results | |
rand.Seed(time.Now().UnixNano()) | |
piggyBank := 0.0 | |
for piggyBank <= bankThreshold { | |
coin := coin() | |
piggyBank += coin | |
fmt.Printf("Coin: %5.2f: Bank %5.2f\n", coin, piggyBank) | |
} | |
fmt.Printf("%4.2f or %v\n", piggyBank, piggyBank) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment