注意:递归一定要有跳出条件,否则很容易栈溢出!!!
下面是一个算到10的加法表:
0 + 0 = 0 0 + 1 = 1 0 + 2 = 2 0 + 3 = 3 0 + 4 = 4 0 + 5 = 5 0 + 6 = 6 0 + 7 = 7 0 + 8 = 8 0 + 9 = 9 0 +10 = 10
1 + 0 = 1 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 1 + 4 = 5 1 + 5 = 6 1 + 6 = 7 1 + 7 = 8 1 + 8 = 9 1 + 9 = 10
2 + 0 = 2 2 + 1 = 3 2 + 2 = 4 2 + 3 = 5 2 + 4 = 6 2 + 5 = 7 2 + 6 = 8 2 + 7 = 9 2 + 8 = 10
3 + 0 = 3 3 + 1 = 4 3 + 2 = 5 3 + 3 = 6 3 + 4 = 7 3 + 5 = 8 3 + 6 = 9 3 + 7 = 10
4 + 0 = 4 4 + 1 = 5 4 + 2 = 6 4 + 3 = 7 4 + 4 = 8 4 + 5 = 9 4 + 6 = 10
5 + 0 = 5 5 + 1 = 6 5 + 2 = 7 5 + 3 = 8 5 + 4 = 9 5 + 5 = 10
6 + 0 = 6 6 + 1 = 7 6 + 2 = 8 6 + 3 = 9 6 + 4 = 10
7 + 0 = 7 7 + 1 = 8 7 + 2 = 9 7 + 3 = 10
8 + 0 = 8 8 + 1 = 9 8 + 2 = 10
9 + 0 = 9 9 + 1 = 10
10+ 0 = 10
本题目要求读入1个整数,输出加法表,每一行都算到结果为输入的整数为止。
不允许使用循环,不允许使用循环,不允许使用循环。重要的事情说三遍(括弧笑)
输入格式:
在一行中给出一个正整数N(0≤N≤99)。
输出格式:
按照示例的格式输出左上三角N+M的表,行列都从0开始。
- 加号左边数字占2位、左对齐;
- 加号右边数字占2位、右对齐;
- 结果数字占2位,左对齐。
- 等号两边各一个空格。
- 两个式子之间加一个空格(行末的空格不用去掉)
输入样例:
5
输出样例:
0 + 0 = 0 0 + 1 = 1 0 + 2 = 2 0 + 3 = 3 0 + 4 = 4 0 + 5 = 5
1 + 0 = 1 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 1 + 4 = 5
2 + 0 = 2 2 + 1 = 3 2 + 2 = 4 2 + 3 = 5
3 + 0 = 3 3 + 1 = 4 3 + 2 = 5
4 + 0 = 4 4 + 1 = 5
5 + 0 = 5
思路:
题目要求不能用循环,那就用递归来做!
代码:
先贴一个自己写的代码(输出样例对,但没提交测试):
import java.util.*;
public class 不用循环 {
// 递归一定要有跳出条件,否则栈溢出!!!
static int n, count = 0, num = 0;
// 利用递归输出一行
static void fun(int n) {
if (count + num > n) {
return;
}
else {
System.out.print(count + " " + "+" + " " + num + " " + "=" + " "
+ (count + num) + " ");
num++;
fun(n);
}
}
// 递归嵌套,输出每一行
static void result(int n) {
if (count > n) {
return;
}
fun(n);
System.out.println();
num = 0;// 加数,每一行都得从0开始
count++;// 第几行,即被加数
result(n);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner in = new Scanner(System.in);
n = in.nextInt();
result(n);
}
}
再贴一个老师给的答案(思路一样):
import java.util.*;
public class 不用循环 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
recursion1(0, n);
}
public static void recursion1(int m, int n) {//m是行数,从0开始
if(m<=n) {
//输出一行
recursion2(0, m, n);
System.out.println();
//m+1再输出下一行
recursion1(m+1, n);
}
}
//输出一行
public static void recursion2(int i, int m, int n) {
if(i+m<=n) {
System.out.printf("%-2d+%2d = %-2d ", m, i, (i+m));
recursion2(i+1, m, n);
}
}
}