Appearance
测验1: exercises/quiz1.rs
题目
rust
// quiz1.rs
//
// This is a quiz for the following sections:
// - Variables
// - Functions
// - If
//
// Mary is buying apples. The price of an apple is calculated as follows:
// - An apple costs 2 rustbucks.
// - If Mary buys more than 40 apples, each apple only costs 1 rustbuck!
// Write a function that calculates the price of an order of apples given the
// quantity bought. No hints this time!
//
// No hints this time ;)
// I AM NOT DONE
// Put your function here!
// fn calculate_price_of_apples {
// Don't modify this function!
#[test]
fn verify_test() {
let price1 = calculate_price_of_apples(35);
let price2 = calculate_price_of_apples(40);
let price3 = calculate_price_of_apples(41);
let price4 = calculate_price_of_apples(65);
assert_eq!(70, price1);
assert_eq!(80, price2);
assert_eq!(41, price3);
assert_eq!(65, price4);
}
这个测验主要针对下面几个部分内容:
- 变量
- 函数
- if条件语句
Mary正在买苹果,一个苹果的价格计算如下:
- 一个苹果需要2个Rust币
- 如果Mary购买超过40个苹果,每个苹果只需要1个Rust币
- 编写一个函数,来计算给定数量的苹果订单的价格
题目解析
首先,计算函数的名字为calculate_price_of_apples
,因为是传入苹果数量,返回所有苹果的金额,数量和金额都没有复数,所以我们使用u32类型。
fn calculate_price_of_apples(count: u32) -> u32 {}
接着补充逻辑:
rust
fn calculate_price_of_apples(count: u32) -> u32 {
if count <= 40 {
2 * count
} else {
1 * count
}
}
或者这样:
rust
fn calculate_price_of_apples(count: u32) -> u32 {
let prize = if count <= 40 { 2 } else { 1 };
prize * count
}
说明
- 从逻辑上说,数量不同引起的是单价的不同,所以相对来说第二种写法更合理一点。
- 同时第二种写法也更符合题目里面的考察点:变量、函数、if语句。