简体   繁体   English

C中带逗号的多个三元组?

[英]Multiple Ternary in C with comma?

so I saw this code所以我看到了这段代码

b[2080];
main(j) {
  for (;;) {
    printf("\x1b[H");
    for (j = 1; j < 2080; j++) 
    b[j] = j < 2000 ? (b[j + 79] + b[j + 80] + b[j] + b[j - 1] + b[j + 81]) / 5 : rand() % 4 ? 0 : 512, j < 1840 ? putchar((j % 80) == 79 ? '\n' : " .:*#$H@" [b[j] >> 5]) : 0;
    usleep(20000);
  }
}

so I tried to rewrite it, why even divide 32?所以我试图重写它,为什么还要除以 32?
The array got to declare as global else it won't work.该数组必须声明为全局,否则它将无法工作。 any idea?任何的想法?
also why 512?还有为什么是512? here is my attempt so far, any problem?这是我到目前为止的尝试,有什么问题吗?

for (int j = 1; j < 2080; j++) 
            {
                if (j < 2000) {
                    b[j] = (b[j + 79] + b[j + 80] + b[j] + b[j - 1] + b[j + 81]) / 5;
                }
                else if (rand() % 4 != 0) { // Generate random integers in range 0 to 4
                          b[j] = 0;
                     }
                     else
                     {
                         b[j] = 512;
                     }
                   
                }
            }

Here's the functionally equivalent code with the ternary operators converted into if/else statements:这是将三元运算符转换为if/else语句的功能等效代码:

            if (j < 2000) {
                b[j] = (b[j + 79] + b[j + 80] + b[j] + b[j - 1] + b[j + 81]) / 5;
            } else if (rand() % 4) {
                b[j] = 0;
            } else {
                b[j] = 512;
            }
            if (j < 1840) {
                if ((j % 80) == 79) {
                    putchar('\n');
                } else {
                    putchar(" .:*#$H@"[b[j] / 32]);
                }
            }

As for the question of what does the right shift >> 5 do, it divides by 32 (2 5 ), and then indexes the array " .:*#$H@" with that divided value.至于右移>> 5做什么的问题,它除以 32 (2 5 ),然后用该除以的值索引数组" .:*#$H@"

edit : As for why the array is global, it's probably just to get it initialised to zero without extra code (the whole thing seems to be written as short as possible, eg, using implicit int types and j from the argument).编辑:至于为什么数组是全局的,它可能只是在没有额外代码的情况下将其初始化为零(整个事情似乎写得尽可能短,例如,使用隐式int类型和参数中的j )。

Note that there is an access out of bounds bug in the (original) code: b[j + 81] can be accessed when j is 1999 (since that is < 2000 ), but 1999 + 81 == 2080 , and b[2080] is out of bounds.请注意,(原始)代码中存在访问越界错误: b[j + 81]可以在j1999时访问(因为它是< 2000 ),但是1999 + 81 == 2080b[2080]越界。 You can replace the array with a local int b[2081] = { 0 };您可以用本地int b[2081] = { 0 };替换数组int b[2081] = { 0 }; but it changes the output slightly while fixing the bug.但它在修复错误的同时稍微改变了输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM