java不使用循环构造和Math,用递归输出2的n次方个星号,
时间: 2024-05-10 11:21:22 浏览: 10
以下是Java代码:
```
public class Main {
public static void main(String[] args) {
int n = 5;
printStars(pow(2, n));
}
public static int pow(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * pow(base, exponent - 1);
}
}
public static void printStars(int n) {
if (n > 0) {
System.out.print("*");
printStars(n - 1);
}
}
}
```
解释:
1. `pow` 方法使用递归来计算 2 的 n 次方,如果指数为 0,则返回 1,否则返回基数乘以 base 的 exponent - 1 次方。
2. `printStars` 方法使用递归来输出 n 个星号,如果 n 大于 0,则输出一个星号并调用自身来输出剩下的星号。
相关问题
java递归输出2的n次方个星号
以下是Java递归输出2的n次方个星号的示例代码:
```
public class Main {
public static void main(String[] args) {
int n = 5;
printStars(n);
}
public static void printStars(int n) {
if (n == 0) {
return;
}
printStars(n - 1);
for (int i = 0; i < Math.pow(2, n); i++) {
System.out.print("*");
}
System.out.println();
}
}
```
输出结果为:
```
*
**
****
********
****************
```
用递归算法求2的n次方Java
好的,我来为您展示用递归算法求2的n次方的Java代码:
```
public static int powerOfTwo(int n) {
if (n == 0) {
return 1;
} else {
return 2 * powerOfTwo(n-1);
}
}
```
在这个递归函数中,当参数n为0时,返回1,因为2的0次方为1。否则,返回2乘以递归调用powerOfTwo(n-1)的结果,直到n为0为止。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)