oracle - 编写 PL/SQL 代码生成从 1 到 500 的 Armstrong 数
问题描述
我得到的输出为 a = 1。我采用了一个从 1 到 500 的 for 循环,并在外部 for 循环内使用了 while 循环。
declare
n number;
s number:=0;
r number;
len number;
m number;
begin
for a in 1..500 loop
m:=a;
n:=a;
len:=length(to_char(n));
while(n>0) loop
r:=mod(n,10);
s:=s+power(r,len);
n:=trunc(n/10);
end loop;
if m=s then
dbms_output.put_line('a='||to_char(a)');
end if;
end loop;
end;
解决方案
这个怎么样?
substr
拆分i
为 3 个单独的数字nvl
null
如果这些数字不存在(还),这里是为了避免增加价值
power
函数计算i
的立方- 显示
i
是否等于r
(作为“结果”)
SQL> declare
2 r number;
3 begin
4 for i in 1 .. 500 loop
5 r := power(to_number(substr(to_char(i), 1, 1)), 3) +
6 nvl(power(to_number(substr(to_char(i), 2, 1)), 3), 0) +
7 nvl(power(to_number(substr(to_char(i), 3, 1)), 3), 0);
8
9 if r = i then
10 dbms_output.put_line(i);
11 end if;
12 end loop;
13 end;
14 /
1
153
370
371
407
PL/SQL procedure successfully completed.
SQL>
推荐阅读
- sql - 在 SQL 中,如果值不连续,是否可以按值进行分区
- speech-to-text - 更新 Watson 的 Speech2text 服务的自定义语言模型后出现内部服务器错误
- php - 将 xampp 上的 MySQL 数据库从 Windows 10 复制到 Linux
- c++ - 以命令模式填充地图
- c# - 添加 /p:Platform="Any CPU" 参数强制在 Debug 配置中构建
- c# - 转换列表
.属性到数组 - c++ - 在 C++ 中使用特殊值对字符串向量进行排序以放在末尾
- android - ImageView setImageDrawable 不适用于 ShapeDrawable
- javascript - 莫里斯 js 时间作为 Y 值始终为零
- plc - 如何在 IEEE 754 表示中将 REAL(32 位浮点数)转换为 8 位字节数组?