用rust语言打印圣诞颂歌 “The Twelve Days of Christmas” 的歌词,并利用歌曲中的重复部分(编写循环)
时间: 2024-04-29 14:26:35 浏览: 198
十二天:一个Rust程序,生成圣诞节十二天的歌词
好的,我可以使用 Rust 语言打印出圣诞颂歌 "The Twelve Days of Christmas" 的歌词,并且使用循环来避免重复代码。以下是代码:
```rust
fn main() {
let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];
let gifts = ["a partridge in a pear tree", "two turtle doves", "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"];
for i in 0..12 {
println!("On the {} day of Christmas, my true love sent to me:", days[i]);
for j in (0..=i).rev() {
if j == 0 && i != 0 {
print!("And ");
}
println!("{}", gifts[j]);
}
println!();
}
}
```
使用此代码,我将打印出圣诞颂歌的所有歌词,同时避免了重复代码。感谢您的问题!
阅读全文