Rust 实现摄氏度与华氏度相互转换——Rust语言基础10


本文是为回顾之前的内容所做的第二个小练习。使用 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. 代码分析

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

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

### LlamaIndex 多模态 RAG 实现 LlamaIndex 支持多种数据类型的接入与处理,这使得它成为构建多模态检索增强生成(RAG)系统的理想选择[^1]。为了实现这一目标,LlamaIndex 结合了不同种类的数据连接器、索引机制以及强大的查询引擎。 #### 数据连接器支持多样化输入源 对于多模态数据的支持始于数据收集阶段。LlamaIndex 的数据连接器可以从多个异构资源中提取信息,包括但不限于APIs、PDF文档、SQL数据库等。这意味着无论是文本还是多媒体文件中的内容都可以被纳入到后续的分析流程之中。 #### 统一化的中间表示形式 一旦获取到了原始资料之后,下一步就是创建统一而高效的内部表达方式——即所谓的“中间表示”。这种转换不仅简化了下游任务的操作难度,同时也提高了整个系统的性能表现。尤其当面对复杂场景下的混合型数据集时,良好的设计尤为关键。 #### 查询引擎助力跨媒体理解能力 借助于内置的强大搜索引擎组件,用户可以通过自然语言提问的形式轻松获得所需答案;而对于更复杂的交互需求,则提供了专门定制版聊天机器人服务作为补充选项之一。更重要的是,在这里实现了真正的语义级关联匹配逻辑,从而让计算机具备了一定程度上的‘认知’功能去理解和回应人类意图背后所蕴含的意义所在。 #### 应用实例展示 考虑到实际应用场景的需求多样性,下面给出一段Python代码示例来说明如何利用LlamaIndex搭建一个多模态RAG系统: ```python from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, PromptHelper, ServiceContext from langchain.llms.base import BaseLLM import os def create_multi_modal_rag_system(): documents = SimpleDirectoryReader(input_dir='./data').load_data() llm_predictor = LLMPredictor(llm=BaseLLM()) # 假设已经定义好了具体的大型预训练模型 service_context = ServiceContext.from_defaults( chunk_size_limit=None, prompt_helper=PromptHelper(max_input_size=-1), llm_predictor=llm_predictor ) index = GPTSimpleVectorIndex(documents, service_context=service_context) query_engine = index.as_query_engine(similarity_top_k=2) response = query_engine.query("请描述一下图片里的人物表情特征") print(response) ``` 此段脚本展示了从加载本地目录下各类格式文件开始直到最终完成一次基于相似度排序后的top-k条目返回全过程。值得注意的是,“query”方法接收字符串参数代表使用者想要询问的内容,而在后台则会自动调用相应的解析模块并结合先前准备好的知识库来进行推理计算得出结论。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Imagine Miracle

爱你哟 =^ v ^=

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值