在PL/SQL中反转一个数字

先决条件 PL/SQL简介

null

在PL/SQL代码中,命令组排列在一个块中。与声明或语句相关的块组。 我们在部分中声明变量,在部分中声明变量,在部分中执行变量。

说明: 考虑这个例子,输入=12345。

步骤1:mod(12345,10)=5 版本:=0*10+5=5 数量=楼层(12345/10)=1234

步骤2:mod(1234,10)=4 版本:=5*10+4=54 数量=楼层(1234/10)=123

步骤3:mod(123,10)=3 版次:=54*10+3=543 数量=楼层(123/10)=12

步骤4:mod(12,10)=2 版次:=543*10+2=5432 数量=楼层(12/10)=1

步骤5:mod(1,10)=1 版次:=5432*10+1=54321 数值=楼层(1/10)=0 在步骤5中,num=0不满足while条件,循环终止。

rev=54321

更多示例:

Input : 123456
Output :654321
Input :87459
Output :95478

以下是所需的实施:

SET SERVEROUTPUT ON ;
DECLARE
-- declare a number 'num' for reading actual input
-- declare another number 'rev' that would be reverse of num
num NUMBER;
rev NUMBER;
BEGIN
-- & is used to read input from keyboard
num:=#
-- initialize rev to 0
rev:=0;
-- the loop runs until num is greater than 0
WHILE num>0 LOOP
-- mod function is used to find the modulus/ remainder of num when divided by 10
rev:=(rev*10) + mod(num,10);
-- floor function is used to obtain a result which is an integer
num:=floor(num/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE( 'Reverse of the number is: ' || rev);
END ;
/
-- Program End


输出:

Enter value for num : 157439
Reverse of the number is: 934751

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享