创建并调用MYSQL函数来查找直到n个数字的斐波那契数



我的方法

DELIMITER $$
CREATE FUNCTION fibonacci(num INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE fib1 INT DEFAULT 0;
DECLARE fib2 INT DEFAULT 1;
DECLARE fib3 INT DEFAULT 0;
DECLARE str VARCHAR(255) DEFAULT '01';

IF num = 1 THEN
RETURN fib1;
ELSEIF num = 2 THEN
RETURN CONCAT(fib1, fib2);
ELSE
WHILE num > 2 DO
SET fib3 = fib1 + fib2;
SET fib1 = fib2;
SET fib2 = fib3;
SET num = num - 1;
SET str = CONCAT(str, fib3);
END WHILE;
RETURN str;
END IF;
END $$
DELIMITER ;

如果我使用SELECT fibonacci(6(调用上面的函数;它返回11235而不前导零(0(。如何也显示前导零?

我认为它会帮助你

DELIMITER $$
CREATE FUNCTION fibonacci_number(n INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE f_0 INT default 0;
DECLARE f_1 INT DEFAULT 1;
DECLARE out_fib INT;
DECLARE i INT;
DECLARE f_2 INT;
SET f_0 = 0;
SET f_1 = 1;
SET i = 1;
WHILE (i<=n) DO
SET f_2 = f_0 + f_1;
SET f_0 = f_1;
SET f_1 = f_2;
SET i = i + 1;
END WHILE;
SET out_fib = f_0;
RETURN out_fib;
END $$

相关内容

  • 没有找到相关文章