Created
April 24, 2020 14:52
-
-
Save andreapavoni/a3e079898b53d3f4f0f5dc423bcb8a62 to your computer and use it in GitHub Desktop.
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
// Pizza Party (#8 from https://pragprog.com/book/bhwb/exercises-for-programmers) | |
// Write a program to evenly divide pizzas. Prompt for the number of people, the | |
// number of pizzas, and the number of slices per pizza. Ensure that the number of | |
// pieces comes out even. Display the number of pieces of pizza each person should | |
// get. If there are leftovers, show the number of leftover pieces. | |
// Challenges | |
// * Revise the program to ensure that inputs are entered as numeric values. | |
// * Alter the output so it handles pluralization properly, for example: | |
// * Each person gets 2 pieces of pizza. or | |
// * Each person gets 1 piece of pizza. | |
// * Handle the output for leftover pieces appropriately as well. | |
// * Create a variant of the program that: | |
// * prompts for the number of people and the number of pieces each person wants | |
// * and calculate how many full pizzas you need to purchase. | |
use std::env; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let people: u32 = parse_cli_arg((&args[1]).to_string()); | |
let pizzas: u32 = parse_cli_arg((&args[2]).to_string()); | |
let pizza_slices: u32 = parse_cli_arg((&args[3]).to_string()); | |
let total_slices: u32 = pizza_slices * pizzas; | |
let slices_per_person: u32 = total_slices / people; | |
let slices_leftover: u32 = total_slices % people; | |
println!("{} people with {} pizzas.", people, pizzas); | |
println!("Each person gets {} pieces of pizza.", slices_per_person); | |
println!("There are {} leftover pieces.", slices_leftover); | |
} | |
fn parse_cli_arg(arg: String) -> u32 { | |
match arg.trim().parse() { | |
Ok(num) => num, | |
Err(_) => 0, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment