我仍然是编程新手,所以请容忍我糟糕的语法和逻辑,如果有的话。我一直在用 C 编写一个密码解算器。它从用户那里读取 3 个单词,计算它们的值并将它们打印到屏幕上。(例如send+more=money
-> 9567+1085=10652
)
我尝试了类似于排列算法的东西。它可以进行计算,但对于某些输入,结果会被打印多次:
如何修改我的代码,以便第一次if (n1+n2==n3)
处理下的 printf 命令递归结束并且程序返回到main
函数?
/* Swaps the two elements of an array. */
void swap(int v[], int i, int j) {
int t;
t = v[i];
v[i] = v[j];
v[j] = t;
}
/* Solves the Cryptarithmetic puzzle. */
int solve(int v[], int n, int i, char s1[], char s2[], char s3[], char letters[]) {
int k, m, j, t = 0, power, n1 = 0, n2 = 0, n3 = 0;
if (i == n) {
/*....some codes that
* calculate the value of each input word.....*/
/*This part verifies the values and if they are correct, prints them to screen*/
if (n1 + n2 == n3) {
printf("found!\n");
printf("\n%s : %6d\n", s1, n1);
printf("%s : %6d\n", s2, n2);
printf("%s : %6d\n", s3, n3);
}
} else
for (j = i; j < n; j++) {
swap(v, i, j);
solve(v, n, i + 1, s1, s2, s3, letters);
swap(v, i, j);
}
}