题目:□□□+□□□=□□□,□中可填入数字1-9,输出所有可能的结果,统计个数
<span style="font-size:18px;">package matchDemo;
// 口口口+口口口=口口口,口中可选数字0~9,必须是三位数,只要两个三位数不同,判定为不同情况
//输出所有符合条件的情况</span>
public class MatchDemo {
static int count=0;
static int [] book=new int [10]; //1-9,9个数字,0不算
static int [] a=new int[10]; //1-9,9个格子,0不算
//输出全是0+0=0,问题出在这
// static int add1=a[1]*100+a[2]*10+a[3];
// static int add2=a[4]*100+a[5]*10+a[6];
// static int result=a[7]*100+a[8]*10+a[9];
public static void main(String[] args) {
dfs(1);
System.out.println("共有"+count/2+"种等式");
}
public static void dfs(int step){
int add1=a[1]*100+a[2]*10+a[3];
int add2=a[4]*100+a[5]*10+a[6];
int result=a[7]*100+a[8]*10+a[9];
if(step==10){ //前9个格子都填好数字以后
if (add1+add2==result) {
System.out.println(add1+"+"+add2+"="+result);
count++;
}
}
for(int i=1;i<=9;i++){
if(book[i]==0){
a[step]=i;
book[i]=1;
dfs(step+1);
book[i]=0;
}
}
}
}
把add1,add2,result这三个数,定义成static型的全局变量,结果输出全为0+0=0
这是很严重的错误,定义为初始化时,a数组中所有的元素都是0.因此add1,add2,result这三个数初始化都为0,在后续方法中,虽然改变了a数组的值,但是并没有再给add1,add2,result这三个数赋值,因此会出现这个错误
这样写本身也是不合理的,直接定义在dfs方法中才是最好的选择。