1. 取模运算符%只用于整数运算,对于浮点数使用该运算符将是无效的。
2. 前缀增量与后缀增量的区别:
先看下面的代码:
#include <stdio.h>
int main(void)
{
int a = 1, b = 1;
int aplus, plusb;
aplus = a++; /*后缀*/
plusb = ++b; /*前缀*/
printf("a aplus b plusb \n");
printf("%1d %5d %5d %5d\n", a, aplus, b, plusb);
return 0;
}
运行结果:
显然,a和b都加一了,但aplus是a改变之前的值,而plusb却是b改变之后的值。
再比如,q=2*++a;它会先将a+1,然后再2*a;而q=2*a++却是先2*a,再将积加1。再举个例子:
b = ++i //如果使用i++,b会有不同结果,而如果使用下列语句来代替它:
++i; //第1行
b=i; //如果在第1行使用了i++,b的结果仍会是相同的。
13.增量运算符++与减量运算符--具有很高的结合优先级,只有圆括号比它们的优先级高。所以x*y++相当于(x)*(y++)。
14.在y =( 4 + x++)+(6 + x++);中表达式( 4 + x++)不是一个完整的表达式,所以C不能保证在计算子表达式4 + x++后立即增加x。这里,完整表达式是整个赋值语句,并且分号标记了顺序点,所以C能保证的是在程序进入后续语句前x将被增加两次。C没有指明x是在每个子表达式被计算后增加还是在整个表达式被计算后增加,这就是我们要避免使用这类语句的原因。
15.请看以下代码:
#include <stdio.h>
int main(void)
{
int i=1;
float n;
while(i++<5)
{
n = (float)1/i; // n = 1.0/i;如果写成1/i,则当i>1时,n都会等于0
printf("%f\n",n);
}
return 0;
}
16.请看代码:
#include <stdio.h>
#define FORMAT "%s! C is cool!\n"
int main(void)
{
int num = 10;
printf(FORMAT,FORMAT);
printf("%d\n",++num);
printf("%d\n",num++);
printf("%d\n",num--);
printf("%d\n",num);
return 0;
}
运行结果:
%s! C is cool!
! C is cool!
11
11
12
11
17. while循环语句在遇到第一个分号之后就退出循环,例如以下代码:
#include <stdio.h>
int main(void)
{
int n = 0;
while (n++ < 3); /* line 7 */
printf("n is %d\n", n); /* line 8 */
printf("That's all this program does.\n");
return 0;
}
输出结果:
n is 4
That's all this program does.
由于while(n++ < 3);之后存在分号,因此它只是循环的执行n++,直至它小于3才退出循环,相当于一个空语句,退出循环时n刚好等于4。有时,程序员有意地使用带有空语句的while语句,因为所有的工作都在判断语句中进行。例如,你想要跳过输入直到第一个不为空格或数字的字符,可以使用这样的循环:
while ( scanf ( “%d”,&num ) == 1)
; /*跳过整数输入*/
只要输入一个整数,则scanf()就返回1,循环就会继续。
18. math.h头文件中声明的fabs()函数用于返回一个浮点值的绝对值,即没有代数符号的值。
19.请看代码:
#include <stdio.h>
int main(void)
{
int num = 0;
for (printf("keep entering numbers!\n");num!=6;)
scanf("%d",&num);
printf("that's the one I want!\n");
return 0;
}
输出结果:
keep entering numbers!
1
2
3
4
5
6
that's the one I want!
20. houseprice = 249,500;相当于:
houseprice = 249;
500;
而houseprice = (249,500);相当于houseprice =500;
21.求S=1 + 1/2 + 1/4 + 1/8 + 1/16 +……