下面程序的输出是6。我不知道为什么。当我用手追踪它时,我得到了5

#include<stdio.h>
#include<conio.h>

main()
{
    int i,count=0;
    char *p1="abcdefghij";
    char *p2="alcmenfoip";

    for(i=0;i<=strlen(p1);i++) {
        if(*p1++ == *p2++)
            count+=5;
        else
            count-=3;
    }
    printf("count=%d",count);
}

最佳答案

if(*p1++ == *p2++)是逐字阅读p1p2的。当字符相同时,它将增加count5,否则它将减少3。但是,还有一件事你没有注意到:strlen(p1)在每次迭代中总是不同的,因为p1会改变。因此,在每次迭代中,还需要检查它的值。

p1   p2 count   i   strlen (before entering into the loop body)
a    a   5      0   10
b    l   2      1   9
c    c   7      2   8
d    m   4      3   7
e    e   9      4   6
f    n   6      5   5  <- No more - this is the last one

10-07 19:23
查看更多