能否用PL/SQL解决母牛生小牛的问题

[复制链接]
查看11 | 回复6 | 2019-7-23 10:42:19 | 显示全部楼层 |阅读模式
RT:能否用pl/sql解决 母牛生小牛的问题,
假设现在有一头母牛5(age=5)岁,每年会生一头小母牛,小母牛5岁的时候可以生小母牛(age=5), 母牛在15(age>15)岁的时候死亡(不能在生小母牛),那么20年后共计多少头牛?

回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
躲在角落看大神们的表演
回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
create table cow(cow_id varchar2(32),age int);
--假设开始时 1头,5年后,就有两头母牛:
--20年后,13头:
SQL>
SQL> declare
2l_count int :=0;
3begin
4delete from cow;
5
6for i in 0..floor(20/5) loop
7
8if i=0 then
9insert into cow values (sys_guid(),0);
10else
11
12for j in (select cow_id from cow where age =5;--计算本年5岁及以上的牛有多少
update niu a set a.age=a.age+1;--进入下一年
for d in 1..j loop

insert into niu values(1,0);--新生小牛数量等于本年5岁及以上母牛的数量
end loop;
execute immediate 'delete from niu where age > 15'; --母牛达到16岁时死亡
end loop;
commit;
select count(*) into c from niu;
dbms_output.put_line(c);
end;

回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
solomon_007 发表于 2019-8-22 20:55
create table cow(cow_id varchar2(32),age int);--假设开始时 1头,5年后,就有两头母牛:--20年后,13头 ...

不会才13头那么少吧
回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
xyz辛德福 发表于 2019-8-23 10:29
不会才13头那么少吧

你的很多条件比较模糊,我算的 15年,牛就死了
回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
solomon_007 发表于 2019-8-23 10:37
你的很多条件比较模糊,我算的 15年,牛就死了

他的意思是牛生牛,还有很多数据没有汇总起来
回复

使用道具 举报

千问 | 2019-7-23 10:42:19 | 显示全部楼层
solomon_007 发表于 2019-8-23 10:37
你的很多条件比较模糊,我算的 15年,牛就死了

感谢回复具体一下条件 5岁的时候就可以生小牛,也就是说,去年4岁的小牛,今年5岁,今年就可以生一头小牛,16岁死亡即年龄大于15 ,15岁的时候会生小牛,
我又完善了一下 如下:
create table niu(a number,age number);
truncate table niu;
insert into niu values(1,5);
commit;
select * from niu;
declare
j number;
c number;
begin
insert into niu values(1,0);--第一年出生一头
for i in 1..19 loop --第二年开始判断是否有小牛出生

update niu a set a.age=a.age+1;
execute immediate 'delete from niu where age > 15'; --移除死亡的母牛(年龄大于15岁的)
select count(*) into j from niu where age>=5; --该年有多少头小牛出生
for d in 1..j loop

insert into niu values(1,0);
end loop;
end loop;
select count(*) into c from niu;
dbms_output.put_line(c);
end;
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行