Rust 实现摄氏度与华氏度相互转换 您所在的位置:网站首页 摄氏度和华氏温度转换 Rust 实现摄氏度与华氏度相互转换

Rust 实现摄氏度与华氏度相互转换

2023-12-27 08:23| 来源: 网络整理| 查看: 265

文章目录 1. 题目2. 分析3. 实现3.1. 代码展示3.2. 功能验证 4. 代码分析4.1. 枚举(enum)4.2. 结构体(struct)4.3. match 和 enum 本文是为回顾之前的内容所做的第二个小练习。使用 Rust 实现摄氏度与华氏度温度的转换。

1. 题目

1、要求实现华氏度与摄氏度之间转换温度。

2. 分析

虽然题目较为简单,但其中暗含的意义需要完全剖析。

分析1: 首先需要判断用户传入的数值是华氏度还是摄氏度。既然是温度,那么一定有正有负而且存在小数的可能,选择数据类型我们就用 f64 是再合适不过的。

分析2: 根据用户输入,判断输出的是华氏度还是摄氏度,之后将其数值转换为另一种温度表示方式并打印。(需要清楚两中温度表示方式的转换方法) [注]:华式度 = 32 + 摄氏度 x 1.8; 摄氏度 = (华式度 - 32) / 1.8。(华式单位: °F, 摄氏单位: °C)

3. 实现

希望读者们也可以先自己尝试使用学过的内容完成这道题目,然后再回来和笔者的代码进行对比,若觉得笔者代码有需要改进的地方还望不吝赐教,一起相互学习,共同进步!!

首先和往常一样,新建一个新的工程目录 convert_temp。

imaginemiracle:rust_projects$ cargo new convert_temp Created binary (application) `convert_temp` package imaginemiracle:rust_projects$ cd convert_temp/ imaginemiracle:convert_temp$ ls Cargo.toml src 3.1. 代码展示

笔者实现的代码如下:

use std::io; enum Type { Fahrenheit, Celsius, None } struct Temp { number: f64, temp_type: Type } fn title_print() { println!("Please select one to enter a number in Fahrenheit and Celsius."); } fn get_temp() -> Temp { let mut input = String::new(); let mut temp_input: Temp = Temp { number: 0.0, temp_type: Type::None }; println!("Please enter a key(Key F or f is Fahrenheit, Key C or c is Celsius)"); io::stdin() .read_line(&mut input) .expect("Failed to read line."); match input { mut input_01 if (input_01.trim() == "F") || (input_01.trim() == "f") => { // ch if (&ch[0..1] == "F") || (&ch[0..1] == "f") => { // 与上面条件等价 loop { println!("Enter current temperature in Fahrenheit(°F):"); input_01.clear(); io::stdin() .read_line(&mut input_01) .expect("Failed to read line."); temp_input.temp_type = Type::Fahrenheit; temp_input.number = match input_01.trim().parse::() { Ok(temp) => temp, Err(_) => { println!("Invalid number!"); continue; } }; break; } }, mut input_02 if (input_02.trim() == "C") || (input_02.trim() == "c") => { // ch if (&ch[0..1] == "C") || (&ch[0..1] == "c") { // 与上面代码条件等 loop { println!("Enter current temperature in Celsius(°C):"); input_02.clear(); io::stdin() .read_line(&mut input_02) .expect("Failed to read line."); temp_input.temp_type = Type::Celsius; temp_input.number = match input_02.trim().parse::() { Ok(temp) => temp, Err(_) => { println!("Invalid number!"); continue; } }; break; } } _ => println!("Invalid input.") } temp_input } fn print_temp(temp: Temp) { println!("Current temperature: {} {}", temp.number, match temp.temp_type { Type::Fahrenheit => "°F", Type::Celsius => "°C", _ => "Error" }); } fn convert_temp(mut temp: Temp) { match temp.temp_type { Type::Fahrenheit => { temp.number = (temp.number - 32.0) / 1.8; temp.temp_type = Type::Celsius; }, Type::Celsius => { temp.number = 32.0 + temp.number * 1.8; temp.temp_type = Type::Fahrenheit; }, _ => println!("Error.") } print_temp(temp); } fn main() { title_print(); convert_temp(get_temp()); } 3.2. 功能验证

华氏度转摄氏度:

imaginemiracle:convert_temp$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/convert_temp` Please select one to enter a number in Fahrenheit and Celsius. Please enter a key(Key F or f is Fahrenheit, Key C or c is Celsius) f Enter current temperature in Fahrenheit(°F): 128 Current temperature: 53.33333333333333 °C

摄氏度转华氏度:

imaginemiracle:convert_temp$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/convert_temp` Please select one to enter a number in Fahrenheit and Celsius. Please enter a key(Key F or f is Fahrenheit, Key C or c is Celsius) c Enter current temperature in Celsius(°C): -53.66877 Current temperature: -64.603786 °F

容错功能:

imaginemiracle:convert_temp$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/convert_temp` Please select one to enter a number in Fahrenheit and Celsius. Please enter a key(Key F or f is Fahrenheit, Key C or c is Celsius) aoiewrfujgbfrb Invalid input. Error. Current temperature: 0 Error imaginemiracle:convert_temp$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/convert_temp` Please select one to enter a number in Fahrenheit and Celsius. Please enter a key(Key F or f is Fahrenheit, Key C or c is Celsius) f Enter current temperature in Fahrenheit(°F): 312qwe312e Invalid number! Enter current temperature in Fahrenheit(°F): qweasd3214 Invalid number! Enter current temperature in Fahrenheit(°F): 34342.21.342.432 Invalid number! Enter current temperature in Fahrenheit(°F): 343.345 Current temperature: 172.96944444444446 °C

此代码实现的容错机制为,在开始选择摄氏度或是华氏度时输入错误则直接退出程序并提示输入无效,当已经正确选择了华氏度和摄氏度后,输入了无效的温度值,此时将会循环让用户输入,直到输入正确为止。

4. 代码分析

此代码使用了暂时还没介绍的 enum 和 struct两中数据类型,但有编程基础的朋友应该会很快理解,但笔者觉得还是再啰嗦解释一下。当然读者们也可以选择不使用也是可以实现的。

4.1. 枚举(enum)

Rust 中的枚举不像其他编程语言中的枚举那样直白简单,但在本文不会介绍太多,本文只会针对本文代码中使用的程度做分析,具体的介绍会在后面的文章中展示。如本文代码,这里定义了一个枚举(enum)类型,其中包含了三个枚举变量。

enum Type { Fahrenheit, Celsius, None }

声明并初始化一个枚举变量。

let my_enum = Type::Fahrenheit; 4.2. 结构体(struct)

结构体允许包含多个不同类型的元素(这一点与元组 Tuple 相似,但更加强大)

struct Temp { number: f64, temp_type: Type }

声明并初始化一个结构体。(这里是枚举变量作为结构体其中的一个元素)

let mut temp_input: Temp = Temp { number: 0.0, temp_type: Type::None }; 4.3. match 和 enum

经过前面几篇的学习相信各位已经对 match 表达式熟练使用了。本文这里可以用 enum 类型作为条件,通过 match 表达式匹配相应的代码块中。 应用1:

match temp.temp_type { Type::Fahrenheit => "°F", Type::Celsius => "°C", _ => "Error" }

应用2

match temp.temp_type { Type::Fahrenheit => { temp.number = (temp.number - 32.0) / 1.8; temp.temp_type = Type::Celsius; }, Type::Celsius => { temp.number = 32.0 + temp.number * 1.8; temp.temp_type = Type::Fahrenheit; }, _ => println!("Error.") }

在本文代码中有两处是这样使用的,可以看的出利用枚举作为条件十分的方便。

Boys and Girls!!! 准备好了吗?下一节我们要还有一个小练习要做哦!

不!我还没准备好,让我先回顾一下之前的。 上一篇《Rust 实现斐波那契数列——Rust语言基础09》

我准备好了,掛かって来い(放马过来)! 下一篇《所有权——Rust语言基础11》

觉得这篇文章对你有帮助的话,就留下一个赞吧v* 请尊重作者,转载还请注明出处!感谢配合~ [作者]: Imagine Miracle [版权]: 本作品采用知识共享署名-非商业性-相同方式共享 4.0 国际许可协议进行许可。 [本文链接]: https://blog.csdn.net/qq_36393978/article/details/125805264



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有