从键盘输入一个不大于20的正整数n,分别用while、do-while和for语句计算n!
时间: 2023-06-04 16:05:42 浏览: 191
好的,我会根据您的要求回答您的问题。下面是三个不同的方法计算n!:
使用while循环计算n!
```
#include <stdio.h>
int main()
{
int n, i = 1, product = 1;
printf("请输入一个不大于20的正整数n:");
scanf("%d", &n);
while (i <= n) {
product *= i;
i++;
}
printf("%d! = %d\n", n, product);
return 0;
}
```
使用do-while循环计算n!
```
#include <stdio.h>
int main()
{
int n, i = 1, product = 1;
printf("请输入一个不大于20的正整数n:");
scanf("%d", &n);
do {
product *= i;
i++;
} while (i <= n);
printf("%d! = %d\n", n, product);
return 0;
}
```
使用for循环计算n!
```
#include <stdio.h>
int main()
{
int n, i, product = 1;
printf("请输入一个不大于20的正整数n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
product *= i;
}
printf("%d! = %d\n", n, product);
return 0;
}
```
阅读全文