输入整数n(n>=0),分别利用for循环、while循环、do…while循环求n!,并调试运行成功
时间: 2024-05-31 09:08:00 浏览: 13
以下是Python代码示例:
# for循环
n = int(input("请输入一个非负整数:"))
result = 1
for i in range(1, n+1):
result *= i
print("%d! = %d" % (n, result))
# while循环
n = int(input("请输入一个非负整数:"))
result = 1
i = 1
while i <= n:
result *= i
i += 1
print("%d! = %d" % (n, result))
# do...while循环(Python没有do...while循环,可以使用while True替代)
n = int(input("请输入一个非负整数:"))
result = 1
i = 1
while True:
result *= i
i += 1
if i > n:
break
print("%d! = %d" % (n, result))
相关问题
java语言,输入整数n(n>=0),分别利用for循环、while循环、do…while循环求n!,并调试运行成功
for循环实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
while循环实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = 1;
int i = 1;
while (i <= n) {
result *= i;
i++;
}
System.out.println(n + "! = " + result);
}
}
```
do…while循环实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = 1;
int i = 1;
do {
result *= i;
i++;
} while (i <= n);
System.out.println(n + "! = " + result);
}
}
```
一、要求说明: 1. 请点击出题按钮,下载并打开试题文件 CTK.c ;按试题要求进行操作。 2. 该程序中标有“【____________】”为需要程序填空的标志,考生可以把题干中的代码在编译器中编辑,根据程序的功能,在填空标志处填入合适的代码(覆盖填空标志),并调试运行程序; 3. 完成相关操作后,按本题的程序文件名进行保存并关闭文件;再按本页界面的上传向导选择试题文件,点击【上传到服务器评分】。 二、注意事项: 1. 在填空时,需删除填空标志“【____________】”、确保不会产生语法错误,再根据程序功能填充;调试运行程序。 2. 不得加行、减行、加句、减句。 三、程序功能: 输入若干个整数,计算并输出其中所有正数的和。输入0时表示输入数据结束。 【输入样例】 -3 5 7 -1 3 8 -9 26 0 【输出样例】 49 【程序代码】 #include <stdio.h> int main(void) { int i, n, x, sum; sum =【____________】 ; do { scanf("%d", &x); if(x > 0) { 【____________】 ; } } while(【____________】); printf("%d", sum); return 0; }
#include <stdio.h>
int main(void)
{
int i, n, x, sum;
sum = 0 ; // 初始化为0
do
{
scanf("%d", &x);
if(x > 0)
{
sum += x; // 累加正数
}
}
while(x != 0); // 当输入为 0 时结束循环
printf("%d", sum);
return 0;
}