分别用for. while 和do-while循环语句以及递归方法计算n,并输出算式。用java
时间: 2024-01-24 08:16:45 浏览: 79
Java中for、while、do while三种循环语句的区别介绍
使用for循环:
```java
public static int calculateWithForLoop(int n) {
int result = 0;
String formula = "";
for (int i = 1; i <= n; i++) {
result += i;
if (i == 1) {
formula += i;
} else {
formula += "+" + i;
}
}
System.out.println(formula + "=" + result);
return result;
}
```
使用while循环:
```java
public static int calculateWithWhileLoop(int n) {
int result = 0;
String formula = "";
int i = 1;
while (i <= n) {
result += i;
if (i == 1) {
formula += i;
} else {
formula += "+" + i;
}
i++;
}
System.out.println(formula + "=" + result);
return result;
}
```
使用do-while循环:
```java
public static int calculateWithDoWhileLoop(int n) {
int result = 0;
String formula = "";
int i = 1;
do {
result += i;
if (i == 1) {
formula += i;
} else {
formula += "+" + i;
}
i++;
} while (i <= n);
System.out.println(formula + "=" + result);
return result;
}
```
使用递归方法:
```java
public static int calculateWithRecursion(int n) {
if (n == 1) {
System.out.println("1=1");
return 1;
} else {
int result = n + calculateWithRecursion(n - 1);
System.out.println(getFormula(n) + "=" + result);
return result;
}
}
public static String getFormula(int n) {
if (n == 1) {
return "1";
} else {
return getFormula(n - 1) + "+" + n;
}
}
```
以上代码中,每个方法都用一个循环语句或递归方法计算1到n的和,并输出相应的算式。
阅读全文