【问题标题】:Storing subsets of a array存储数组的子集
【发布时间】:2014-04-14 23:42:20
【问题描述】:

这个程序正在“计算”数组的所有子集。我需要将结果值存储在另一个名为 polje 的 2D 文件中。如果我只使用printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); 代码可以正常工作,但是当它试图将所有内容复制到结果字段时会失败。我想我在数组 polje 的索引中出了点问题。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

        int f;
        int i,j;
        int source[2][3] = {{0,3,5},{3,4,2}};
        int currentSubset = 3;
        int polje[8][3];

        for(i=0;i<8;i++){
                for(j=0;j<3;j++){
                        polje[i][j]=0;
                }}
        int tmp;
        while(currentSubset)
        {
                tmp = currentSubset;
                for( i = 0; i<3; i++)
                {
                        if (tmp & 1)
                        {
                                printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); //writes out everything I want
                                polje[currentSubset][0]=source[i][0];
                                polje[currentSubset][1]=source[i][1];
                                polje[currentSubset][2]=source[i][2];
                        }
                        tmp >>= 1;
                }
                printf("\n");
                currentSubset--;
        }

        for(i=0;i<8;i++){
                for(j=0;j<3;j++){
                        printf("%d ", polje[i][j]);
                }printf("\n");}
        return (EXIT_SUCCESS);
}

输出字段应该是:

0 3 5
3 4 2
3 4 2
0 0 0
0 3 5 
0 0 0
0 0 0
0 0 0

但实际上是:

0 3 5
3 4 2
3 4 2
0 0 0
*0 0 0* 
0 0 0
0 0 0
0 0 0

【问题讨论】:

  • int tmp; while(currentSubset) { tmp = currentSubset; 对我来说看起来很糟糕。可以做得更简单。

标签: c arrays subset


【解决方案1】:

tmp 是一个只有两位的位掩码,所以内部循环应该是for ( i = 0; i &lt; 2; i++ )

另外,polje 数组的正确索引是 polje[currentSubset * 2 + i][0],因为 polje 中的每个 subset 需要两个空格,而 i 是 0 或 1。

【讨论】:

    【解决方案2】:

    我认为你只是有一个逻辑错误。你的循环的骨架是:

    currentSubset = 3;
    while ( currentSubset )
    {
    // ...
        polje[currentSubset][...] = ...;
    // ...
        currentSubset--;
    }
    

    因此,除了前三行之外,您永远不会写入任何行。

    【讨论】:

    • 哦,是的,现在很明显,关于如何存储数组有什么想法吗?
    • 确保您可以手动完成您想要的算法(例如在纸上或在您的脑海中)。然后将其分解为您希望程序执行的小步骤列表;然后检查你的程序是否实现了这些步骤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    相关资源
    最近更新 更多