using nested for loop to print all of factorial
47 次查看(过去 30 天)
显示 更早的评论
Hi.
I want to print the factorial of each number from 1 to 100 using a nested loop.
Here is my program.
factorials = 1; % set a varaiable named factorial
for n = 1:100 % set a nested for loop
for i= 1:n
factorials = factorials * i; % when n = 1;i = 1; f = 1*1
disp(factorials); % display results
end
end
The expected result shoule be 1, 2, 6,24........
When i run my code, the result are inf.
Why it happened?
And how to modify my code?
Thank you all.
0 个评论
采纳的回答
DGM
2022-6-16
编辑:DGM
2022-6-16
Something like this should be a start:
for n = 1:100 % set a nested for loop
factorials = 1; % this needs to be reset inside the loop
for i = 1:n
factorials = factorials * i; % when n = 1;i = 1; f = 1*1
end
disp(factorials); % display only the final result for each n
end
0 个评论
更多回答(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!