2

我仍然是编程新手,所以请容忍我糟糕的语法和逻辑,如果有的话。我一直在用 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);
        }
}
4

2 回答 2

3

需要进行三个更改。首先,一旦你解决了它,你需要返回一些东西:

    printf ("%s : %6d\n", s3 , n3);
    return 1;

接下来需要在递归的时候检查返回值,找到解决办法就停止:

    if (solve (v, n, i+1,s1,s2,s3,letters))
        return 1;

最后,如果找不到解决方案,则需要返回 0:

    }
    return 0;
}
于 2014-12-07T21:18:25.167 回答
1

你可以使用setjmp()/longjmp(). 为此,您需要:

#include <setjmp.h>

然后是一个全局变量:

jmp_buf env;

然后在 main (或任何你调用递归函数的地方)你做:

if(!setjmp(env)) recursiveSolve();

然后当你找到解决方案时:

if(solutionFound) longjmp(env, 1);

它会像什么都没发生一样返回到 main - 但是找到了您的解决方案。

于 2017-08-13T19:08:43.320 回答