using nested for loop to print all of factorial
47 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
DGM
le 16 Juin 2022
Modifié(e) : DGM
le 16 Juin 2022
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!