代码中与零的连接没有正确发生?
我试图在 PL/SQL 中反转一个数字。它工作正常,但是当我的数字包含任何 0 时,输出是意外的。例如:
1234 output 4321
1000 output 1
1203 ouput 3021
10001 output 1
DECLARE
r number(9);
num number(9):=&p_num;
BEGIN
WHILE num>=1 LOOP
IF mod(num,10)=0 THEN -- extracting last digit of a number .
r:=r||0; --if end digit is 0 then concat r with 0
ELSE
r:=r||mod(num,10);--if mod is not 0 then it would be last digit.
END IF;
num:=trunc(num/10);--Removing last digit from number
END LOOP;
dbms_output.put_line(r);
END;
I was trying to reverse a number in PL/SQL. It's working fine, but when my number contains any 0, the output is unexpected. For example:
1234 output 4321
1000 output 1
1203 ouput 3021
10001 output 1
DECLARE
r number(9);
num number(9):=&p_num;
BEGIN
WHILE num>=1 LOOP
IF mod(num,10)=0 THEN -- extracting last digit of a number .
r:=r||0; --if end digit is 0 then concat r with 0
ELSE
r:=r||mod(num,10);--if mod is not 0 then it would be last digit.
END IF;
num:=trunc(num/10);--Removing last digit from number
END LOOP;
dbms_output.put_line(r);
END;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试将变量“r”的类型更改为 varchar2。
由于它被声明为数字,因此前导零将被丢弃。
Try changing the type of the variable "r" to varchar2.
Since it's declared as number, leading zeros are discarded.
“反转数字”本质上是一种字符串操作,而不是数字操作。从数字上看,10、100、1000 等的倒数都是 1 - 结果中的前导零不算在内。因此,该操作不是可逆的;所有具有相同前导(有效)数字和零个或多个尾随零的数字在反转时都会产生相同的输出。
因此,您需要修改代码以生成字符串,而不是数字。
'Reversing a number' is fundamentally a string operation, not a numerical one. Numerically, the reverse of 10, 100, 1000, etc are all 1 - the leading zeroes in the result don't count. And the operation is not, therefore, invertible; all numbers with the same leading (significant) digits and with zero or more trailing zeroes produce the same output when reversed.
So, you need to revise your code to generate a character string, not a number.
你不能用数字保留前导零;您必须使用字符串 (varchar2)。尝试这样的事情来看看:
You can't preserve leading zeros with numbers; you must use strings (varchar2). Try something like this to see:
我不确定你的代码 Vineet 出了什么问题,但也许这会起作用。
编辑:或者正如 gabe 正确指出的那样,只需使用 REVERSE 函数即可。
I'm not sure what's going wrong in your code Vineet but perhaps this will work.
Edit: Or as gabe correctly points out, just use the REVERSE function.
问题是你正在处理一个 NUMBER 值。当你反转 1000 时,你会得到 0001,当输出未格式化时,它是 1。
你真正需要的是类似于:
The problem is you're dealing with a NUMBER value. When you reverse 1000, you get 0001, which when output unformatted is 1.
What you really need is something akin to: