用T-SQL流程控制语句编写程序,求两个数的最大公约数和最小公倍数

2025-05-10 13:39:57
推荐回答(1个)
回答1:

因为你的代码中,@c的最后值一直 是2,也就是说,goto label1 会一直执行下去
下面这段代码能够实现你的需求

DECLARE @a int,@b int,@c int,@d int,@gongyueshu int,@gongbeishu int
set @a=18
set @b=6
if(@a = 0 or @b = 0)
begin
set @gongyueshu = 0
set @gongbeishu = 0
end
else
begin
declare @atemp int ,@btemp int
set @atemp = @a
set @btemp = @b
set @gongyueshu = 1
if(@a > @b)
set @c = @b
else
set @c = @a
if @c = 1
begin
set @gongbeishu = @a * @b
end
else
begin
set @d = 2
lable1:
if @d > @c or @d > @a or @d > @b
goto lable2
if @a % @d = 0 and @b % @d = 0
begin
set @a = @a / @d
set @b = @b / @d
set @gongyueshu = @gongyueshu * @d
goto lable1
end
else
begin
set @d = @d +1
goto lable1
end

lable2:set @gongbeishu=@atemp*@btemp/@gongyueshu

select '最大公约数是:' + cast(@gongyueshu as varchar(10))
select '最小公倍数是:' + cast(@gongbeishu as varchar(10))
end
end