c - C 中计数和计数位的输出不正确

标签 c arrays loops bit

这只是我的第二堂编程课。有30个房间。我们必须查看每个房间里有什么并进行统计。我已经使用 for 循环遍历了 30 个房间,并且我知道我已尝试使用位计数器来查看每个房间中的内容。重定向示例输出后,我没有获得正确的示例输出。当我 printf("%d", itemCnt[loc]); 时,我的输出是 774778414trolls

当我 printf("%d", itemCnt[0]); 时,我的输出是 0trolls。我只是想获得正确的一个输出,这样我就可以弄清楚如何获得其余 8 个输出。从示例输出来看,第一个数字应该是 6,然后是 6、1、4、4 ...,依此类推。下面是示例输入/输出以及我到目前为止的代码。

示例输入:

1   20  @@
2   21  @A
3   22  @#
4   23  @1
5   22  @@
6   22  @@
7   22  @@
8   22  @@
9   23  @Z  Here be trolls � not!
10  23  @+
12  23  @@
13  24  @@
11  22  @@
14  22  @2
15  21  @1
16  20  @@
17  19  @@
18  20  @@
19  19  @@
20  18  @@
21  17  @*
22  16  @*
23  15  @%
0   14  @7
0   gold_bar
1   silver_bar
2   diamond
3   copper_ring
4   jumpy_troll
5   air
6   angry_troll
7   plutonium_troll

示例输出:

6   gold_bar
6   silver_bar
1   diamond
4   copper_ring
4   jumpy_troll
8   air
15  angry_troll
0   plutonium_troll

代码

int main()
{
    // contains x and y coordinate
    int first, second;
    char third[100];
    char fourth[100];
    char Map[30][30];

    // map initialization
    for(int x=0; x<30; x++){
        for(int y=0; y<30; y++){
            Map[x][y] = '.';
        }
    }

    while(scanf("%d %d %s",&first, &second, third) != -1) {
        // Condition 1: a zero coordinate
        if (first==0 || second==0) exit(0);
        // Condition 2: coordinate out of range
        if (first<0 || first>30 || second<0 || second>30){
            printf("Error: out of range 0-30!\n");
            exit(1);
        }


        Map[second-1][first-1] = third[1];
        fgets(fourth, 100, stdin);

        // bit counter
        int itemCnt[8] = {0};         // array to hold count of items, index is item type
        unsigned char test;           // holds contents of room.
        int loc;
        for(loc = 0; loc < 8; loc++)  // loop over every bit and see if it is set
        {
            unsigned char bitPos = 1 << loc;  // generate a bit-mask
            if((test & bitPos) == bitPos)
                ++itemCnt[loc];
        }
        // print the map
        for(int h=0; h<30; h++){
            for(int v=0; v<30; v++){
                printf("%c", Map[h][v]);
            }
            printf("\n");
            }
        // print values
        printf("%d", itemCnt[0]);

    }

    return 0;
}

最佳答案

test 未初始化。您似乎打算将“third[1]”分配给test

此外,774778414 = 十六进制的 0x2E2E2E2E,0x2E 是 ASCII '.' 的数值,即 map 位置的初始值。 (提示:当您看到这样的百搭小数时,请尝试 Google。我输入了“十六进制的 774778414”,不带引号。)

我还建议将代码分解为两个函数:第一个从 stdin 读取以填充 Map(就像您所做的那样),第二个从 stdin 读取以填充 8 个 C 字符串来描述您的对象。需要注意的是,第一个循环不应该持续到输入结束,因为您发布的输入继续是描述,而不是像开头那样严格的 3 个字段。

关于c - C 中计数和计数位的输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216267/

相关文章:

jQuery : loop through nested objects

javascript - 将数组转换为对象

c - 在哪里可以找到c源代码

c - 为什么下面的 C 代码中我的 Wordsize 是 64 位?

c - C语言输出字符串的三元运算

c# - 具有多个值的 ArrayList c#

c - 测试用例中的段错误

syntax - 在PLT方案中循环

arrays - 如何使用 node.js 将多个 json 对象合并到一个 json 文件中

跨平台条件无限循环