知识点
函数定义
递归函数
阶乘
编程
代码
use std::io;
//main 函数,它是很多程序的入口点
fn main() {
println!("请输入一个正整数:");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("输入失败!");
let x: u32 = input.trim().parse().expect("请输入正整数!");
println!("{}!是{}", x, factorial(x)); //调用函数
}
//定义函数
/// # 功能
/// 给定一个正整数计算阶乘
/// # 参数
/// 'x' 正整数
/// # 返回值
/// 阶乘计算结果
/// # 示例
/// ```
/// let result = factorial(5); //计算正整数5的阶乘
/// assert_eq!(result, 120); //检查函数的输出是否正确
/// // 5*4*3*2*1
/// ```
fn factorial(x: u32) -> u32 {
if x == 1 || x == 0 {
return 1;
}
x * factorial(x - 1)
}