简体   繁体   English

printf打印的值有误

[英]Wrong value being printed by printf

I have this piece of C code 我有这段C代码

#include <stdio.h>

int main(){
        int i , j , m , A[5]={0,1,15,25,20};
        i = ++A[1];
        printf("%d:\n",i);

        j = A[1]++;
        printf("%d:\n",j);

        m = A[i++];
        printf("%d:\n",m);

        printf("%d %d %d",i,j,m);
        return 0;
}

and It's output is 它的输出是

2:
2:
15:
3 2 15

Shouldn't the printf print the values as 2 , 2, 15 but why is it printing 3 , 2, 15 printf不应该将值打印为2,2,15,但是为什么要打印3,2,15呢?

PS : I really didn't abuse this code , someone else did (my professor perhaps) and I'm just learning C . PS:我确实没有滥用此代码,其他人(也许是我的教授)也滥用了代码,而我只是在学习C。

The line 线

m = A[i++];

will increment the variable i in-place after it gets the cooresponding value from the array A. 从数组A获得对应的值后,它将就地增加变量i。

我作为以下语句的一部分递增

       m = A[i++];

m = A[i++]; m = A [i ++];

this code assign A[2] which is 15 to the variable m ,and then +1 to the current value of i to become 3. 此代码将变量m的A [2]赋值为15,然后将i的当前值+1变为3。

Lets see what we got here.. 让我们看看我们到了这里。

int i , j , m , A[5]={0,1,15,25,20}; int i,j,m,A [5] = {0,1,15,25,20};

    i = ++A[1];  // takes the value of A[1], increment it by 1 and assign it to i. now i = 2, A[1] = 2
    printf("%d:\n",i);
    j = A[1]++; // takes the value of A[1](which is 2), assign it to j and increment the value of A[1] by 1. now j = 2, A[1] = 3
    printf("%d:\n",j);

   //remember the value of i? its 2
    m = A[i++]; // takes the value of A[2](which is 15), assign it to m and increment the value of i by 1. now m = 15, i = 3
    printf("%d:\n",m);

    printf("%d %d %d",i,j,m); // Hola! we solve the mystery of bermuda triangle :)
    return 0;

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

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