content
Code 1: - - operator || operator
The output of running the following program is:
//运行以下程序,输出结果是?
#include <stdio.h>
int main()
{
int a,b,c;
a=1; b=2; c=3;
a=b--<=a||a+b!=c;//首先a取值应当为1或者0。
//b--<=a 取值应为假,故为0;(2<1显然为假,)
//a+b!=c 取值应为真,故为1;(1+1!=3显然对√)0||1 =1,故a=1。
printf("a=%d,b=%d\n",a,b); //故输出 a=1,b=1。
}
output:
The reason is explained in the comments!
Code 2: Mandatory type conversion such as (int) (5.0/2), priority understanding
//运行以下程序的输出结果是? a=3
#include <stdio.h>
int main()
{
int a;
a=(int)((double)(3/2)+0.5+(int)1.99*2);
//首先a是整型的,所以0.5应该取整为0,又(double)(3/2)=1.500000,
//对于(int)1.99*2,应该理解为,1.99取整为1,然后1*2=2
//所以 a=1.5+2=3.500000,取整,所以a=3
printf("a=%d\n\n",a); //a=3
printf("----------------\n\n");
printf("测试_1:(int)1.99*2 = %d\n\n",(int)1.99*2); //2
printf("测试_1:(int)(1.99*2) = %d\n\n",(int)(1.99*2)); //3
//由测试结果可知,(int)1.99*2 确实应该是先对1.99取整为1,再 1*2=2
}
output:
The comments are very clear!
Code 3: Coercion type conversion operator
//求以下表达式的值 a=4
#include <stdio.h>
int main()
{
int a;
a=(int)((double)(5/2) + 2.5);
//首先, (double)(5/2)=2.000000。因为5/2=2,又double,所以为2.000000
//其次,2+2.5=4.5。取整,故a=4
printf("a=%d\n",a); // a=4
}
output:
Code 4: Self-addition operators ++i and i++
//运行以下程序的输出结果是
#include <stdio.h>
int main()
{
int i=8,j=9,m,n;
m=++i; //m=9 i=9
n=j++; //n=9 j=10
printf("i=%d,j=%d,m=%d,n=%d\n",i,j,m,n);
//故 i=9,j=10,m=9,n=9
}
output:
Code 5: Priority question (error-prone questions need to be reviewed multiple times)
//易错题
//运行以下程序的输出结果为: i=1,j=2,k=0
#include <stdio.h>
int main()
{
int k,i=0,j=2;
k=i++ && j++ ;
//错误思路×××: 0 && 2,结果为假 取0,故k=0。之后,i和j再分别自加,故 i=1,j=3
//以上错误的原因是,把最终结果当成了 "k=多少?"
//正解√:&&作为分隔符,先算左边的,即先是k=i++,此时k=0,i=1,&&左边取值为0
//由于 && 运算符,一假则假,故 (k=i++ && j++)取值即为0,
//即 && 右边不执行,所以j仍然为原值,即j=2
printf("答案:i=%d,j=%d,k=%d\n\n",i,j,k);
printf("------------------------------\n\n");
//为便于测试,故重新定义变量q相当于k,同时i和j赋回原来的值。
int q; i=0,j=2;
printf("测试:\n\n");
printf("(q=i++) && (j++) = %d\n\n",(q=i++) && (j++)); //0
printf("------------------------------\n\n");
printf("继续测试:\n\n");
int m; i=0,j=2;
printf("m=i++取值为:%d\n",m=i++); //0
printf("j++取值为:%d\n\n",j++); //2
printf("------------------------------\n\n");
printf("再次测试:\n\n");
int p; i=0;j=2;
printf("p=i++ && j++ = %d\n",p=i++ && j++); //0
}
output:
For this question, please combine the following three tests "Eat". I was "going through the cracks" during the testing process. In the end, it can be seen that && is actually used as the separator. First, the value on the left of && is calculated, that is, k=0, i=1, and the value on the left of && is 0, so the right side is no longer calculated (the right side is not executed), so we get The result of i=1, j=2, k=0 is obtained. In fact, the final result of the expression k=i++ && j++ ; is 0. ( 0 &&()=0
)
If the order of operations is wrong, it is easy to make mistakes, just as the "wrong idea" written in the comments.