gpt4 book ai didi

c - 循环 #3 中的 printf() 函数给出了意外的结果

转载 作者:行者123 更新时间:2023-11-30 19:30:12 26 4
gpt4 key购买 nike

有 3 个循环,其中最后一个循环的行为不符合预期。循环 #2 和循环 #3 是糟糕的代码样式。他们来这里只是为了演示。问题是为什么循环 #3 中的 printf() 给出了意外的输出,而循环#2 中的 printf() 给出了预期的结果?这个错误是因为编译器还是因为 printf 函数?是否有任何文档可以解释编译器或某些函数在某些情况下的行为方式,以便我可以查找 future 的问题。

int main(void){

int mat1[3][4] = {4,5,0,3,0,0,1,2,0,0,0,6};

//****************** Output 1 ***********************************************

for(int i=0; i<3;i++)
for(int j=0;j<4;j++){
printf("%d, ", mat1[i][j]);
if(j==3)printf("\n");
}


/* Expected output 1:

4 5 0 3
0 0 1 2
0 0 0 6
*/

printf("\n\n");

//******************* Output 2 ************************************************

for(int i=0; i<3;i++)
for(int j=0;j<4;j+=4)

printf("\n%d, %d, %d, %d", mat1[i][j+0],mat1[i][j+1],mat1[i][j+2],mat1[i][j+3]);



/* Expected output 2:

4 5 0 3
0 0 1 2
0 0 0 6
*/

printf("\n\n");

//********************* Output 3 **********************************************

for(int i=0; i<3;i++)
for(int j=0;j<4;j)

printf("\n%d, %d, %d, %d", mat1[i][j++],mat1[i][j++],mat1[i][j++],mat1[i][j++]);


/* Unexpected output 3:

3 0 5 4
2 1 0 0
6 0 0 0
*/

}

最佳答案

    printf("\n%d, %d, %d, %d", mat1[i][j++],mat1[i][j++],mat1[i][j++],mat1[i][j++]);

这是非常糟糕的编码风格,但发生的情况是 printf 在打印出 j 之前从右到左评估它们。这就是为什么在第一个 mat1[i][j++] j 将为 3,在第二个为 2,依此类推,直到最后一个 mat1[i][j++] 将具有 j 将为 0。

关于c - 循环 #3 中的 printf() 函数给出了意外的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com