Rust learning: lessons, notes, and exercise crates
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "grader"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "grader"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,63 @@
|
||||
use std::env;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() < 2 {
|
||||
println!("usage : cargo run -- [score]");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut scores: Vec<u32> = Vec::new();
|
||||
for arg in &args[1..] {
|
||||
match arg.parse::<u32>() {
|
||||
Ok(score) => {
|
||||
println!("{score} -> {}", grade_score(score));
|
||||
scores.push(score);
|
||||
}
|
||||
Err(_) => println!("{arg} not a number"),
|
||||
}
|
||||
}
|
||||
|
||||
if scores.is_empty() {
|
||||
println!("not a valid score");
|
||||
} else {
|
||||
println!("average scores: {}", average(&scores));
|
||||
}
|
||||
|
||||
println!("{args:?}");
|
||||
}
|
||||
|
||||
fn grade_score(score: u32) -> String {
|
||||
match score {
|
||||
90..=100 => "A".to_string(),
|
||||
80..90 => "B".to_string(),
|
||||
70..80 => "C".to_string(),
|
||||
_ => "F".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn average(scores: &Vec<u32>) -> u32 {
|
||||
let mut total = 0;
|
||||
for s in scores {
|
||||
total = total + s;
|
||||
}
|
||||
|
||||
total / scores.len() as u32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grade_map_to_letters() {
|
||||
assert_eq!(grade_score(95), "A");
|
||||
assert_eq!(grade_score(70), "B");
|
||||
assert_eq!(grade_score(43), "F");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_of_three() {
|
||||
assert_eq!(average(&vec![80, 90, 70]), 80);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user