五、 运算号、表达式和语句
3. 其他运算符
3.1 suzeof 运算和size_t 类型
// sizeof.c -- 使用 sizeof 运算符
// 使用 C99 新增的%zd转换说明 -- 如果编译器不支持%zd,请将其改成%u或%lu
#include <stdio.h>
int main (void)
{
int n = 0;
size_t intsize;
intsize = sizeof (int);
printf("n = %d, n has %zd bytes; all ints have %zd bytes.\n",
n, sizeof n, intsize);
return 0;
}
//n = 0, n has 4 bytes; all ints have 4 bytes.
3.2 求模运算符:%
// min_sec.c -- 把秒数转换成分和秒
#include <stdio.h>
#define SEC_PER_MIN 60 // 1分钟60秒
int main(void)
{
int sec, min, left;
printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit):\n");
scanf("%d", &sec); // 读成秒数
while (sec > 0)
{
min = sec / SEC_PER_MIN; //截断分钟数
left = sec % SEC_PER_MIN; //剩下的秒数
printf("%d seconds is %d minutes, %d seconds.\n", sec,
min, left);
printf("Enter next value (<=0 to quit):\n");
scanf("%d", &sec);
}
printf("Done!\n");
return 0;
}
//Convert seconds to minutes and seconds!
//Enter the number of seconds (<=0 to quit):
//154
//154 seconds is 2 minutes, 34 seconds.
//Enter next value (<=0 to quit):
//567
//567 seconds is 9 minutes, 27 seconds.
//Enter next value (<=0 to quit):
//0
//Done!
3.3 递增运算符:++
■ ++在前
■ ++在后
/* add_one.c -- 递增: 前缀和后缀 */
#include <stdio.h>
int main (void)
{
int ultra = 0, super = 0;
while (super < 5)
{
super++;
++ultra;
printf("super = %d, ultra = %d \n", super, ultra);
}
return 0;
}
//super = 1, ultra = 1
//super = 2, ultra = 2
//super = 3, ultra = 3
//super = 4, ultra = 4
//super = 5, ultra = 5
//改写5.2(shoes2.c)一部分代码:
shoe = 3.0;
while (shoe < 18.5)
{
foot = SCALE * shoe + ADJUST;
printf("%10.1f %20.2f inches\n", shoe, foot);
++shoe;
}
//再改写,运用递增运算符
shoe = 2.0;
while (++shoe < 18.5)
{
foot = SCALE * shoe + ADJUST;
printf("%10.1f % 20.2f inches\n", shoe, foot);
}
/* post_pre.c -- 前缀和后缀 */
#include <stdio.h>
int main(void)
{
int a = 1, b = 1;
int a_post, pre_b;
k
a_post = a++; //后缀递增
pre_b = ++b; //前缀递增
printf("a a_post b pre_b \n");
printf("%1d %5d %5d %5d\n", a, a_post, b, pre_b);
return 0;
}
//a a_post b pre_b
//2 1 2 2