Executing two loops at the same time
1 次查看(过去 30 天)
显示 更早的评论
What I am trying to do is applying different calculations depending on whether the number is odd or even.
n = input('Your number = ');
i = 1;
while n ~= 1
while rem(n,2) == 0
n = (n/2);
i = i + 1;
end
while rem(n,2) == 1
n = (3*n) + 1;
i = i + 1;
end
end
i
This is what I have currently. However when I enter n, the script runs forever and I have to restart the matlab. How can I make this loop to continue until n reaches 1?
0 个评论
采纳的回答
JESUS DAVID ARIZA ROYETH
2017-9-21
you can do like this:
n = input('Your number = ');
i = 1;
while n ~= 1
while rem(n,2) == 0 && n ~= 1
n = (n/2);
i = i + 1;
end
while rem(n,2) == 1 && n ~= 1
n = (3*n) + 1;
i = i + 1;
end
end
i
更多回答(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!