下面程序的运行结果是
#include<stdio.h>
int main()
{ char ch[7]={"65ab21"};
int I,s=0;
for(I=0;ch[I]>='0'&&ch[I]<='9';I+=2)
s=10*s+ch[I];
printf("%d",s); }
char类型可以提升为int类型,比如字符'0'提升为int类型后,值是48,也就是字符'0'的ASCII码值。
你 这段代码的执行过程如下:
I = 0 时,ch[I] = '6',满足for循环条件,s = s * 10 + ch[I] = 0 * 10 + 54 (这个54是'6'的ASCII码值) = 54; I+=2=2
I = 2 时,ch[I] = 'a',不满足for循环条件, 循环结束,所以此时 s的值就是54
根据代码来看,这个代码的目的是将字符串中开头的数字转换成整数。但为啥要I+=2呢?应该I++啊,而且应该s= 10 * s + ch[I] - '0'才对啊。否则这段代码真不知道干啥用了
#include<stdio.h>
int main(){
char ch[7]={"65ab21"};
//检查字符转为数字都是什么值
int m=0;
int length=sizeof(ch)/sizeof(ch[0]);
for(m=0;m<length;m++)
printf("%d\n",ch[m]);
printf("-----------------------\n");
int I,s=0;
for(I=0;ch[I]>='0'&&ch[I]<='9';I+=2){
s=10*s+ch[I];
printf("%d\n",ch[I]);
printf("%d\n",I);
printf("%d\n",s);
printf("========");
}
}
把代码改一下更有利于学习和研究。
直接学习这种代码,就是没有必要的增加复杂度,打击研究动力。