content
Code 1: The priority problem
//下列各个表达式取值为?
#include <stdio.h>
int main()
{
printf("已知: a=3,b=4,c=5\n\n");
printf("则有:\n\n");
int a=3,b=4,c=5;//显然b==c为假,故取值为0
printf("(a+b>c && b==c) = %d\n\n",a+b>c && b==c);
a=3,b=4,c=5;//先看&&右边,b-c=-1(非0)为真,右边取1。而&&左边有个||,又a=3(非0),故&&左边亦取1。因此整个表达式为1。
printf("(a||b+c && b-c) = %d\n\n",a||b+c && b-c);
a=3,b=4,c=5;//!c取0,而无论前边怎么取,取0还是取1,后边有个||,还有1,故最终结果为1
printf("(!(a>b)&&!c||1) = %d\n\n",!(a>b)&&!c||1);
a=3,b=4,c=5;//&&右边,c/2为2,2+4=6(非0),故&&右边取1。再看&&左边,a+b=7,!(a+b)取0,0+c-1=4为非0,故&&左边取1。所以整个表达式取1
printf("(!(a+b)+c-1 && b+c/2) = %d\n",!(a+b)+c-1 && b+c/2);
}
output:
The topic is simple, I think I made it clear in the comments!
Code 2: Accuracy problem
//精度问题。。。
#include <stdio.h>
int main()
{
int x;
float y=5.5; //y*3=16.500000
x=(float)(y*3+((int)y)%4); //首先 (int)y=5,其次 ((int)y)%4=1
printf("x=%d\n\n",x);
printf("-----------\n\n");
printf("测试:\n\n");
printf("(int)y = %d\n\n",(int)y);
printf("((int)y) %% 4 = %d\n\n",((int)y)%4);
printf("y*3=%f\n\n",y*3);
printf("(float)(y*3+(((int)y)%4) = %f\n",(float)(y*3+((int)y)%4));
//又由于x是整型,所以17.500000取整为17
}
output:
Here, I am a little bit tricky about the printout format of %.
This topic is very basic and simple, and it should be well understood by combining the annotation and testing parts.
Code three: (?:) expression evaluation
//?:表达式求值
#include <stdio.h>
int main()
{
int x=1,y=1;
int a=1,b=4,c=3,d=2;
printf("!x || y-- = %d\n\n",!x || y--);//!x取值为0,y--取值为1,故0||1取值为1。
printf("a<b?a:c<d?c:d = %d\n\n",a<b?a:c<d?c:d);
printf("-------------------------\n\n");
printf("测试:\n\n");
printf("((a<b)?(a):(c<d?c:d)) = %d\n\n",((a<b)?(a):(c<d?c:d)));
//对于上式,a<b为真,直接取a=1,最后结果亦为1 (后边不再执行)。c<d为假,取d=2。
printf("-------------------------\n\n");
printf("再次测试:\n\n");
printf("a<b?a:666 = %d\n\n",a<b?a:666); //1<4 √√ 故取a=1
printf("c<d?c:d = %d\n\n",c<d?c:d); //3<2 ×××故取d=2
return 0;
}
Test output:
I think the comment has already said it more clearly!
Code 4: Relax for a moment ~ ~!
//轻松一刻 ~ ~!下列程序的输出结果为
#include <stdio.h>
int main()
{
int a=1,b=2,c;
int x=97;
c=1.0/b*a; //首先1.0/b 即 1.0/2 = 0.500000,而后 0.5*a 即0.500000*1=0.500000
//又因为c为整型,故c最后取整为 0
printf("c=%d\n",c);
printf("x=%c\n",x);
printf("x=%d\n",x);
}
output: