Hi there! Today is the day 2 challenge. The goal is to compute the total cost of a meal given the meal price, tip percent and tax percent. Usually when I go to a restaurant in Brazil I only care about the first two, as taxes are already included in the meal price. Again: this is pretty basic, but as I am used to other languages syntax this simple tutorial from HackerRank is being quite useful to keep me training everyday and learn Go, so it is awesome! Now, let’s see my solution:
package main
import (
"fmt"
"math"
)
// Round to nearest integer
func Round(f float64) uint32 {
up := math.Floor(f)
down := math.Ceil(f)
if math.Abs(f-up) < math.Abs(f-down) {
return uint32(up)
}
return uint32(down)
}
func main() {
mealCost := 0.0
tipPercent := 0.0
taxPercent := 0.0
// Read variables in sequence
// and separated by new lines
//I have never tried this in C,
//but I think it probably works
fmt.Scanf("%v\n%v\n%v\n", &mealCost,
&tipPercent, &taxPercent)
// Answer is the total cost rounded
// to the nearest dollar
totalCost := Round(mealCost *
(1.0 + (tipPercent+taxPercent)/100.0))
fmt.Printf("The total meal cost
is %v dollars.\n", totalCost)
}
Today I didn’t find a round function in the math
package. I don’t know if
Google is going to implement it, but I had this custom implementation to get the
meal cost to the nearest dollar. I forgot about Scanf
and tried Scanln
first
with the same arguments, but of course it didn’t work and that’s why my solution
uses Scanf
.
That’s all for day 2. Thanks for reading!