bin
러스트 프로그래밍 가이드 연습문제 1 ~ 3
satorare
2022. 10. 23. 14:53
1. 화씨와 섭씨를 상호 변환.
use std::io;
fn main() {
println!("Input the temperature: ");
let mut temp = String::new();
io::stdin().read_line(&mut temp).expect("Failed to read_line");
let temp: f32 = temp.trim().parse().expect("Failed to parse");
println!("Select the option : \n 1) Convert Celsius to Fahrenheit. \n 2) Convert Fahrenheit to Celsius.");
let mut option = String::new();
io::stdin().read_line(&mut option).expect("Failed to read_line");
let option: i32 = option.trim().parse().expect("Failed to parse");
match option {
1 => {
c_to_f(temp);
},
2 => {
f_to_c(temp);
},
_ => println!("invaild option. please correct input")
}
}
fn c_to_f(t: f32) {
let converted_t = t * 1.8 + 32.0;
println!("{} is convert to {}", t, converted_t);
}
fn f_to_c(t: f32) {
let converted_t = (t - 32.0) * 5.0 / 9.0;
println!("{} is convert to {}", t, converted_t);
}
함수 c_to_f는 섭씨(Celsius)온도를 화씨(Fahrenheit)온도로 변환합니다.
함수 f_to_c는 화씨온도를 섭씨온도로 변환합니다.
온도를 먼저 입력받은 다음, 변환 방법을 선택하면 그에 맞게 변환되어 섭씨 혹은 화씨 온도가 출력됩니다.
온도와 관련된 변수들은 소수점을 표시할 수 있도록 f32 타입으로 설정하였습니다.
2. n번째 피보나치 수열 생성.
use std::io;
use std::cmp::Ordering;
fn main () {
println!("Input the number for create to Fibonacci Numbers.");
let mut num = String::new();
io::stdin().read_line(&mut num).expect("Failed to read_line");
let num: u32= num.trim().parse().expect("Failed to parse");
println!("Fibonacci Numbers of {} is {}", num, fibonacci(num));
}
fn fibonacci(n: u32) -> u32 {
match n.cmp(&3) {
Ordering::Less => 1,
_ => fibonacci(n - 2) + fibonacci(n - 1)
}
}
함수 fibonacci는 매개변수로 주어진 값에 해당하는 순서의 피보나치 수를 반환합니다.
피보나치 수열은 재귀함수를 통하여 구현하였습니다.
3. 크리스마스 캐롤 “The Twelve Days of Christmas”의 가사를 반복문을 활용해 출력.
fn main() {
let carol = ["A partridge in a pear tree",
"Two turtle doves",
"Three Frnech hens",
"Four calling birds",
"Five golden rings",
"Six geese a laying",
"Seven swans a swimming",
"Eight maids a milking",
"Nine ladies dancing",
"Ten lords a leaping",
"Eleven pipers piping",
"Twelve drummers drumming"];
println!("~~ The Twelve Days of Christmas ~~");
for index in 0..12 {
println!("Day {} : {}", index + 1, carol[index]);
}
}
The Twelve Days of Christmas 캐롤은 1 ~ 12일 별로 그 구절이 나눠져 있으며, 이를 연속적인 값의 형태인 배열로 구현하였습니다.
반복문을 이용하여 carol 배열의 색인을 불러들여 일별로의 구절들을 하나씩 출력합니다.