1 计算n的阶乘
1.输入n 2.1*2*3*……*n 3.打印结果
代码1展示:(for循环)
1. #include <stdio.h> 2. int main() 3. { 4. int n = 0; 5. int i = 1; 6. int b = 1; 7. scanf("%d", &n); 8. for (i = 1; i <= n; i++) 9. { 10. b = b * i; 11. } 12. printf("%d ", b); 13. return 0; 14. }
代码2展示:(while循环)
1. #include <stdio.h> 2. int main() 3. { 4. int n = 0; 5. int i = 1; 6. int b = 1; 7. scanf("%d", &n); 8. while (i <= n) 9. { 10. b = b * i; 11. i++; 12. } 13. printf("%d ", b); 14. return 0; 15. }
代码3展示:
1. #include <stdio.h> 2. int main() 3. { 4. int n = 0; 5. int i = 1; 6. int b = 1; 7. scanf("%d", &n); 8. do 9. { 10. b = b * i; 11. i++; 12. } while (i <= n); 13. printf("%d", b); 14. return 0; 15. }
2 计算1!+2!+3!+4!+5!+6!+7!+8!+9!+10!
阶乘相加
代码1展示:(易错点,b每次都要初始化)
1. #include <stdio.h> 2. int main() 3. { 4. int n = 0; 5. int i = 1; 6. int b = 1; 7. int j = 1; 8. int sum = 0; 9. for (j = 1; j <= 10; j++) 10. { 11. int b = 1; 12. for (i = 1; i <= j; i++) 13. { 14. b = b * i; 15. } 16. sum = sum + b; 17. } 18. printf("%d", sum); 19. return 0; 20. }
代码2展示:(不容易想出来,多看看这个代码)
1. #include <stdio.h> 2. int main() 3. { 4. int n = 0; 5. int b = 1; 6. int j = 1; 7. int sum = 0; 8. for (j = 1; j <= 10; j++) 9. { 10. b = b * j; 11. sum = sum + b; 12. } 13. printf("%d", sum); 14. return 0; 15. }