求n!(n为键盘输入的任意整数值)。要求分别用while语句和for语句实现
用while语句实现:
#include <stdio.h> int main() { int n; scanf("%d",&n); int result = 1; while(n) { result *=n; n--; } printf("%d\n",result); }
用for语句实现:
#include <stdio.h> int main() { int n, i; scanf("%d",&n); int result = 1; for(i=1;i<=n;i++) { result *=i; } printf("%d\n",result); }
用递归函数实现:
1 #include <stdio.h> 2 int fact(int n) 3 { 4 if(n==0) return 1; 5 return n*fact(n-1); 6 } 7 8 int main() 9 { 10 int n; 11 scanf("%d",&n); 12 int result = fact(n); 13 printf("%d",result); 14 15 return 0; 16 }