Rust编程基础语法学习:从Hello World到温度转换

IT巴士 3 0

fn main() {

println!("Hello, Rust world!");

}

let tup: (i32, f64, char) = (500, 6.4, '嗨'); let arr = [1, 2, 3, 4, 5];

let s1 = String::from("hello"); let len = calculate_length(&s1); // 借用s1

fn calculate_length(s: &String) -> usize {

s.len()

} // s离开作用域,但不会清理数据

fn convert_temperature(value: f64, unit: char) -> Option {

match unit {
    'F' => Some((value - 32.0) * 5.0/9.0),
    'C' => Some(value * 9.0/5.0 + 32.0),
    _ => None,
}

}

fn main() {

let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let value: f64 = input.trim().parse().unwrap_or_default();

input.clear();
std::io::stdin().read_line(&mut input).unwrap();
let unit = input.trim().chars().next().unwrap_or('C');

if let Some(result) = convert_temperature(value, unit) {
    println!("转换结果: {:.2}", result);
} else {
    println!("请输入F或C表示温度单位");
}

}

标签: #Rust编程入门 #Rust基础语法 #Rust字符串处理 #Rust函数定义 #Rust温度转换示例

上一篇掌握Kotlin代码调试技巧:提升开发效率的秘密武器

下一篇当前文章已是最新一篇了