在 pl/sql 中打印奇数和偶数

时间:2021-02-14 11:15:59

标签: sql oracle plsql

我是编程新手;我想在循环中打印奇数和偶数,问题是 if 不起作用,无论您输入什么数字,它都会打印 else:

DECLARE
x NUMBER:=:x;
r NUMBER:=:r;
BEGIN
LOOP
if x/2=0 AND r/2!=0 then
dbms_output.put_line('Even number x='||x);
dbms_output.put_line('Odd number r='||r);
x:= x+2;
r:= r+2;
else
dbms_output.put_line('Odd number x='||x);
dbms_output.put_line('Even number r='||r);
x:=x+2;
r:=r+2;
exit when x>20 and r>20;
end if;
end loop;
end;

1 个答案:

答案 0 :(得分:1)

您需要使用 mod(x,2)=0 来检查它是否为偶数,而不是 x/2=0。我已经分离了 x 和 r 的条件。查看以下代码:

    DECLARE
x NUMBER:=2;
r NUMBER:=3;
BEGIN
LOOP
if mod(x,2)=0 then
dbms_output.put_line('Even number x='||x);
else
dbms_output.put_line('Odd number x='||x);
end if;

if mod(r,2)=0 then
dbms_output.put_line('Even number r='||r);
else
dbms_output.put_line('Odd number r='||r);
end if;
x:= x+2;
r:= r+2;

exit when x>20 and r>20;

end loop;
end;