display while loop output as an array
3 次查看(过去 30 天)
显示 更早的评论
how do you display the output of a while loop as an array.
code:
function [] = hailstone_sequence(n)
n = input('Value for n: ');
h = 1;
while(n~=1)
if n==1
return
elseif mod(n,2)
n=3*n +1
else
n=n/2
end
h=h+1;
end
采纳的回答
Walter Roberson
2017-10-5
Just before the h=h+1 insert
output(h) = n;
2 个评论
Walter Roberson
2017-10-5
Then move it to after the while() statement.
But question: does the output need to include the 1? If so then make sure to add a 1 to the end before the return statement.
更多回答(1 个)
jean claude
2017-10-5
编辑:jean claude
2017-10-5
function [output] = hailstone_sequence(n)
output=[n];
h = 1;
while(n~=1)
if n==1
return
elseif mod(n,2)
n=3*n +1
else
n=n/2
end
h=h+1;
output= [output n];
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!