==1、==多组数据同时输入,需要借助如下语句结构:
try
while 1
line = input('', 's');
lines = strsplit(line);
printf("%d\n", str2num(lines{
1}) + str2num(lines{
2}));
end
catch
end
因此,在下列例题中:
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
【本题有多组数据。】
多组数据的暗示为需要借助上述语句来完成多次输入,因此代码可以如下写出:
clear
try
while 1
M = input('');
newRabit = [1,1];
TmptotalNum = newRabit;
for i=1:M
N = size(TmptotalNum,1);
for n=1:N %at the begining of each new month, birth of new rabbits
if TmptotalNum(n,2)>=3
TmptotalNum = [TmptotalNum;newRabit];
end
end
TmptotalNum(:,2) = TmptotalNum(:,2) + 1;%the next month age of each rabbit
end
fprintf('%d\n',size(TmptotalNum,1));
end
catch
end
The process that rabbits have birth to new rabbit can be describe as another pieces:
repmat(A, m, 1);复制向量A成为矩阵m行一列的矩阵
TmptotalNum = [TmptotalNum;repmat(newRabit,sum(TmptotalNum(:,2)>=3),1)]