Files
spl/stage1/test18_recursion.spl
2026-07-05 21:45:43 +08:00

37 lines
744 B
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ===== 模块6函数 =====
* test18_recursion — 递归函数
* 难度3/5
* 验证点:递归调用、多路递归、递归终止条件
*/
fn fib(n: i32) i32 {
if n <= 1 { ret n; }
ret fib(n - 1) + fib(n - 2);
}
fn fact(n: i32) i32 {
if n <= 0 { ret 1; }
ret n * fact(n - 1);
}
fn main() i32 {
/* 斐波那契 */
var f0 := fib(0);
if f0 != 0 { ret 1; }
var f1 := fib(1);
if f1 != 1 { ret 2; }
var f5 := fib(5);
if f5 != 5 { ret 3; }
var f10 := fib(10);
if f10 != 55 { ret 4; }
/* 阶乘 */
var fact0 := fact(0);
if fact0 != 1 { ret 5; }
var fact3 := fact(3);
if fact3 != 6 { ret 6; }
var fact5 := fact(5);
if fact5 != 120 { ret 7; }
ret 0;
}