Help on my function script?
9 次查看(过去 30 天)
显示 更早的评论
My function is [s,m]=collatz(the input number) which I used x=input('Enter a natural number:'). If I want an even input to be divided by 2, and an odd input to be multiplied by 3 plus 1. This goes on as long as the number is greater than one. Ex: starting with 3 it would give 3-10-5-16-8-4-2-1. How would I set this up?
function[s,m]=collatz()
x=input('Enter a natural number:')
while mod(x,2)==0 %shows x(natural number) is even
x=x/2
if mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
end
end
0 个评论
采纳的回答
Fangjun Jiang
2018-9-25
almost there
while x>1
if mod(x,2)==0 %shows x(natural number) is even
x=x/2
elseif mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
end
end
1 个评论
Fangjun Jiang
2018-9-25
编辑:Fangjun Jiang
2018-9-25
to prevent infinite loop when the input is a decimal number, for example 3.2, modify it as below
x=input('Enter a natural number:');
while x>1
if mod(x,2)==0 %shows x(natural number) is even
x=x/2
elseif mod(x,2)==1 %shows x(natural number) is odd
x=x*3+1
else
x
break;
end
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!