销售物品
本课属于 Coddy Rust 学习旅程的“逻辑与流程”单元。第 52 课,共 66 课。
挑战
简单你会收到 5 个输入。第一个输入是要出售的商品名称。第二个输入是要出售的数量。第三个输入是库存中以逗号分隔的商品名称列表。第四个输入是与每件商品对应、以逗号分隔的价格列表。第五个输入是与每件商品对应、以逗号分隔的数量列表。创建一个 HashMap 来存储库存数据,其中键是商品名称,值是一个元组,包含价格和数量 (f64, i32)。然后尝试出售指定数量的商品。
要求:
- 从
std::collections导入HashMap - 读取第一个输入(要出售的商品名称)并去除空白字符
- 读取第二个输入(要出售的数量)并去除空白字符
- 将要出售的数量解析为
i32 - 读取第三个输入(以逗号分隔的商品名称)并去除空白字符
- 读取第四个输入(以逗号分隔的价格)并去除空白字符
- 读取第五个输入(以逗号分隔的数量)并去除空白字符
- 为库存创建一个可变的
HashMap<String, (f64, i32)> - 按逗号拆分商品名称
- 按逗号拆分价格,并将每个价格解析为
f64 - 按逗号拆分数量,并将每个数量解析为
i32 - 将每件商品及其对应的价格和数量作为元组插入库存
- 使用
.get()检查库存中是否存在指定商品 - 使用
match表达式处理.get()返回的Option - 在
Some分支中:- 从元组中提取价格和当前数量
- 检查当前数量是否大于或等于要出售的数量
- 如果是:
- 用当前数量减去要出售的数量,计算新的数量
- 用商品价格乘以要出售的数量,计算总价
- 使用
.insert(),将库存更新为新的数量 - 打印:
Sold [quantity_to_sell] [item_name] - 打印:
Total: $[total_price] - 打印:
Remaining stock: [new_quantity]
- 如果不是(库存不足):
- 打印:
Insufficient stock for [item_name] - 打印:
Available: [current_quantity]
- 打印:
- 在
None分支中,打印:[item_name] is not in stock
输入:
- 第一行:要出售的商品名称(例如,
Mouse) - 第二行:要出售的数量(例如,
10) - 第三行:以逗号分隔的商品名称(例如,
Laptop,Mouse,Keyboard) - 第四行:以逗号分隔的价格(例如,
999.99,25.50,75.00) - 第五行:以逗号分隔的数量(例如,
15,50,30)
输出:
- 如果商品存在且库存充足:
- 第一行:
Sold [quantity_to_sell] [item_name] - 第二行:
Total: $[total_price] - 第三行:
Remaining stock: [new_quantity]
- 第一行:
- 如果商品存在但库存不足:
- 第一行:
Insufficient stock for [item_name] - 第二行:
Available: [current_quantity]
- 第一行:
- 如果商品不存在:
[item_name] is not in stock
亲手试试
use std::collections::HashMap;
use std::io;
fn main() {
// 读取输入
let mut item_to_sell = String::new();
io::stdin().read_line(&mut item_to_sell).expect("Failed to read line");
let item_to_sell = item_to_sell.trim();
let mut quantity_to_sell_input = String::new();
io::stdin().read_line(&mut quantity_to_sell_input).expect("Failed to read line");
let quantity_to_sell: i32 = quantity_to_sell_input.trim().parse().expect("Invalid number");
let mut item_names_input = String::new();
io::stdin().read_line(&mut item_names_input).expect("Failed to read line");
let item_names_input = item_names_input.trim();
let mut prices_input = String::new();
io::stdin().read_line(&mut prices_input).expect("Failed to read line");
let prices_input = prices_input.trim();
let mut quantities_input = String::new();
io::stdin().read_line(&mut quantities_input).expect("Failed to read line");
let quantities_input = quantities_input.trim();
// TODO: 在下方编写你的代码
// 创建一个 HashMap 来存储库存
// 处理输入并建立库存
// 检查商品是否存在,并处理销售
}逻辑与流程中的所有课
自己练习: Rust 在线编译器