The Rust Programming Language
0. proconio
Cargo.toml
[dependencies]
proconio = "0.4.5"
1. 温度の変換
温度を華氏と摂氏で変換する。
$ ^\circ C = (^\circ F - 32) \times 5 \div 9 $
use proconio::input;
fn main() {
input! {
f: f64
}
println!("{}", to_c(f));
}
fn to_c(f: f64) -> f64 {
(f - 32.0) * 5.0 / 9.0
}
$ ^\circ F = (^\circ C \times 9 \div 5) + 32 $
use proconio::input;
fn main() {
input! {
c: f64
}
println!("{}", to_f(c));
}
fn to_f(c: f64) -> f64 {
(c * 9.0 / 5.0) + 32.0
}
2. フィボナッチ数列
フィボナッチ数列のn番目を生成する。
$ F_0 = 0, \ F_1 = 1, $
$ F_{n + 2} = F_n + F_{n + 1} \ (n \ge 0) $
use proconio::input;
fn main() {
input! {
n: u32 // 符号なし整数
}
println!("{}", fibonacci(n));
}
fn fibonacci(n: u32) -> u32 {
if n < 2 {
n
} else {
fibonacci(n - 2) + fibonacci(n - 1)
}
}
3. The Twelve Days of Christmas
クリスマスキャロルの定番、"The Twelve Days of Christmas"の歌詞を、 曲の反復性を利用して出力する。
fn main() {
// 序数と歌詞を用意
const ORDINAL_NUMBERS: [&str; 12] = [
"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth",
];
const LYRICS: [&str; 12] = [
"A partridge in a pear tree", "Two turtle doves, and",
"Three french hens", "Four calling birds",
"Five gold 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",
];
// i + 1 番の歌詞を出力
for i in 0..12 {
println!(
"On the {} day of Christmas, my true love sent to me",
ORDINAL_NUMBERS[i],
);
for j in (0..i + 1).rev() {
println!("{}", LYRICS[j]);
}
println!();
}
}