
2个回答
展开全部
clear
S=54; %数组总和
Amin=0; %数据最小值
Amax=5; %数据最大值
SumA=S-1;
n=0;
while SumA<S
n=n+1;
temp=Amax+1;
while temp>Amax
temp=Amin+fix((Amax+1-Amin)*rand(1));
end
STemp=SumA+temp;
if STemp<=S
A(n)=temp;
SumA=sum(A);
else
n=n-1;
end
end
%%%%%%%%%%%%%%%%%%%
% 下面的程序是保证数据随机性追加的,以弥补上面程序数据结尾一定不为0的缺陷
while STemp==S
n=n+1;
temp=Amax+1;
while temp>Amax
temp=Amin+fix((Amax+1-Amin)*rand(1));
end
STemp=S+temp;
if STemp==S
A(n)=temp;
end
end
A %需要的数组
sum(A) %数组总和
下面是输出结果(每次执行都会有不同的输出):
A = 1 1 4 3 4 4 2 1 2 1 3 5 3 3 0 3 2 1 2 3 4 1 0 1 0
A= 1 1 0 3 2 2 3 4 0 0 1 5 3 4 2 2 1 1 1 5 0 0 2 5 1 2 2 0 0 1
S=54; %数组总和
Amin=0; %数据最小值
Amax=5; %数据最大值
SumA=S-1;
n=0;
while SumA<S
n=n+1;
temp=Amax+1;
while temp>Amax
temp=Amin+fix((Amax+1-Amin)*rand(1));
end
STemp=SumA+temp;
if STemp<=S
A(n)=temp;
SumA=sum(A);
else
n=n-1;
end
end
%%%%%%%%%%%%%%%%%%%
% 下面的程序是保证数据随机性追加的,以弥补上面程序数据结尾一定不为0的缺陷
while STemp==S
n=n+1;
temp=Amax+1;
while temp>Amax
temp=Amin+fix((Amax+1-Amin)*rand(1));
end
STemp=S+temp;
if STemp==S
A(n)=temp;
end
end
A %需要的数组
sum(A) %数组总和
下面是输出结果(每次执行都会有不同的输出):
A = 1 1 4 3 4 4 2 1 2 1 3 5 3 3 0 3 2 1 2 3 4 1 0 1 0
A= 1 1 0 3 2 2 3 4 0 0 1 5 3 4 2 2 1 1 1 5 0 0 2 5 1 2 2 0 0 1
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询