入门的阶乘算法
程序代码:
int b,d; scanf("%d",&b); while(b>=1 && b<=9) { d=b; } while(d>=1) { b=b*d; d=d-1; } printf("%d",b); system("pause"); return 0;
要求算1~9中任意数的阶乘,能运行,但是结果不正确.....这个要咋改啊
#include <stdio.h> long factorial(long num) { if (num == 1) return 1; else return num * factorial(num - 1); } int main() { int num = 0, innum = 0; printf("请输入需要计算阶乘最大数\n"); scanf("%d", &innum); for(num=1; num<=innum; num++) printf("%2d的阶乘等于 %d\n",num, factorial(num)); }
#include <stdio.h> long factoral(int num) { long x = 1; int y = 0; for (y = 1; y <= num; y++) { x = x * y; } return x; } int main() { int num = 0, innum = 0; printf("请输入需要计算阶乘最大数\n"); scanf("%d", &innum); for (num = 1; num <= innum; num++) { printf("%2d的阶乘等于 %d\n", num, factoral(num)); } return 0; }