当前位置:网站首页>Rust语言——小小白的入门学习10
Rust语言——小小白的入门学习10
2022-07-16 01:17:00 【ImagineMiracle】
本文是为回顾之前的内容所做的第二个小练习。使用 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::<f64>() {
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::<f64>() {
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语言——小小白的入门学习09》
我准备好了,掛かって来い(放马过来)!
下一篇《Rust语言——小小白的入门学习11》
觉得这篇文章对你有帮助的话,就留下一个赞吧v*
请尊重作者,转载还请注明出处!感谢配合~
[作者]: Imagine Miracle
[版权]: 本作品采用知识共享署名-非商业性-相同方式共享 4.0 国际许可协议进行许可。
[本文链接]: https://blog.csdn.net/qq_36393978/article/details/125805264
边栏推荐
- 【Jailhouse 文章】Bao: a modern lightweight embedded hypervisor(2020)
- 图片格式解析
- Unity (c) method for obtaining the encoding format of files
- Differences among screenwidth, clientwidth, offsetwidth, and scrollwidth
- PDF手册|1666页 Zabbix6.0官方中文 操作手册PDF免费领!
- Common audio features: Mel spectrum, amplitude spectrum (short time Fourier transform spectrum /stft), Mel cepstrum (MFCC)
- Typescript learning summary
- YGG established a new subdao - YGG Japan
- Database system probability -- relational database
- Traditional gyms are trapped in large-scale, and Lexus sports "s2b2c" mode is the reference answer?
猜你喜欢

Matlab drawing_ 1 draw attenuation oscillation curve
![[LSTM regression prediction] Based on MATLAB tpa-lstm time attention mechanism, long-term and short-term memory neural network regression prediction (multiple input and single output) [including Matla](/img/78/3d0256bb44e199270560e57a18dac8.png)
[LSTM regression prediction] Based on MATLAB tpa-lstm time attention mechanism, long-term and short-term memory neural network regression prediction (multiple input and single output) [including Matla

Power Bi ---- what is a measure?

Solution: referenceerror: PubSub is not defined

MySQL original field to hump naming

【idea】idea添加vm options

面试高频:MySQL是怎么保证高可用的?

Hidden Markov model (HMM)

Power BI----到底什么是度量值?

openEuler 知:repo
随机推荐
[load balancer does not contain an instance for the service mall coupling] and the project start normally but cannot register with Nacos
使用nlmeas对图像进行去噪
If the designer leaves, the iphone14 may become a brick, and using the iPhone is even more compelling
【鸡汤】天下事有难易乎
ThreadLocal夺命11连问 我实在扛不住呀
UE5簡單的角色碰撞檢測功能
openEuler 知:SIG
图片格式解析
Kettle【实践 02】txt类型文件分类导入后执行SQL进行数据类型转换并入库(完整流程实例云资源分享:包含sql+kjb+ktr+测试文件)
第50篇-某查查请求头参数分析【2022-07-14】
Power bi---- DAX explanation
Common audio features: Mel spectrum, amplitude spectrum (short time Fourier transform spectrum /stft), Mel cepstrum (MFCC)
In three steps, I finished MySQL in one day, which made me win tmall offer smoothly
The sandbox alpha Season 3 first Trailer
UE4_ Ue5 play audio (play, stop function) (attached project)
Kettle【实践 01】Linux环境下使用Azkaban定时调用Kettle的KJB或KTR脚本实现自动化数据处理(完整流程实例分享:包含sql+ktr+shell+flow相关文件云资源)
Image format analysis
包含数字的字符串剔除字母根据步长递增
uniapp uni-popup change
Typescript learning summary