c - 生成 K 个数字中 6 个的所有可能组合

标签 c numbers

我有一个作业,其中不允许我使用“[]”,并且只能使用指针来完成。
到目前为止,我的代码工作正常,但我在打印 6 个 K 数字的所有可能组合时遇到了问题。
这是我的代码:

    # include <stdio.h>
    int main() {
    system("chcp 1253");

    int a, i, j, temp, *ar, k, I, J, K;
    printf("Numbers must be 6 or 49.\n"); /*User can enter 6-49 numbers*/
    scanf("%d",&a);
    while(a<6 || a>49) {
            printf("Wrong, choose again: \n");
            scanf("%d", &a);
        } 

    ar = (int*) malloc(a*sizeof(int)); /*Creating array*/

    system("cls");
    printf("Choosing numbers*/
    for (i=0; i<a; i++) {
        scanf("%d", ar+i);
        while (*(ar+i)<1 || *(ar+i)>49) { /*Numbers must be greater than 1 and less than 49*/
        printf("Wrong number, choose again: \n");
        scanf("%d", ar+i);
        }
    }

    for (i=0; i<a; i++) { /*Sorting array*/
        for (j=i+1; j<a; j++) {
            if (*(ar+i) > *(ar+j)) {
                temp = *(ar+i);
                *(ar+i) = *(ar+j);
                *(ar+j) = temp;
            }
        }
    }

    printf("\n\n"); /*Printing all possible 6 combinations of K numbers*/
    for(i=1; i<=a-5; i++) {
        for(j=i+1; j<=a-4; j++) {
            for(k=j+1; k<=a-3; k++) {
                for(I=k+1; I<=a-2; I++) {
                    for(J=I+1; J<=a-1; J++) {
                        for(K=J+1; K<=a; K++) {
                            printf("%d|%d|%d|%d|%d|%d|\n", *(ar), *(ar+i), *(ar+j), *(ar+k), *(ar+I), *(ar+J));
                            }
                        }
                    }
                }
            }
        }


    free(ar);
    return 0; 
}

假设用户输入了 6 个数字,组合的打印是正确的 (1|2|3|4|5|6)。
但是如果用户选择其他任何东西,例如 7 个数字,结果是:

1|2|3|4|5|6
1|2|3|4|5|6
1|2|3|4|5|7
1|2|3|4|6|7
1|2|3|5|6|7
1|2|4|5|6|7
1|3|4|5|6|7

我被卡住了,我不知道自己出了什么问题,有什么提示吗?
我 95% 确定错误出在 printf 上,但我尝试了几次更改,但都没有奏效。
对不起我的英语,
干杯,
代词

最佳答案

我发现了我的问题,当用户输入数字时,我的代码是这样的:

printf("Choosing numbers*/
    for (i=0; i<a; i++) {
        scanf("%d", ar+i);

在打印组合时,“i”被设置为 1。所以我在“选择数字”处更改了“i”,并将其设置为 i=0:

printf("Choosing numbers*/
        for (i=1; i<a; i++) {
            scanf("%d", ar+i);

现在一切正常!无论如何,谢谢你的时间!

关于c - 生成 K 个数字中 6 个的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48287605/

相关文章:

Java 长数字帮助

string - Lisp:将数字转换为字符串

java - 连接到 Java 客户端的 C 服务器套接字问题

c++ - 如何在不使用信号量的情况下解决寿司吧问题?

xpath - XPath 1.0 中的总结

c++ - 用C++添加整数

javascript - 错误添加负数jquery

c - 无需循环即可将字节数组转换为整数的方法?

c - 永无止境的快速排序

无法在 CodeBlocks : Undefined reference to 'WinMain@16' 上编译 C 程序