sizeof运算符以字节为单位返回其操作数的大小(在c中,1个字节被定义为char类型所占用空间的大小。在过去,一个字节通常是8位,但是一些字符集可能使用更大的字节)
sizeof实例程序:
1
2
3
4
5
6
7
8
9
10
11
12
|
#include<stdio.h>
int
main()
{
int
n=0;
size_t
intsize;
intsize=
sizeof
(
int
);
//c规定sizeof返回size_t类型的值,这是一个无符号整数类型,但不是一个新类型,
printf
(
"n=%d,n has %u bytes:all ints have %u bytes.\n"
,n,
sizeof
n,intsize);
//我的系统%zd无法实现,所以用%u(%lu)来替代。
return
0;
//c有个typedef机制,它允许您为一个已有的类型创建一个别名。如:typedef double real; 使得real 称为duble 的别名,real deal;编译器看到real,回想起typedef 语句把real定义为double的别名,于是把deal创建为一个double类型的变量。
}
|
运行结果:
2、取模运算:while()循环:
实例程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//min_sec.c把秒数转换为分钟和秒
#include<stdio.h>
#define SEC_PRE_MIN 60
int
main()
{
int
sec=60;
int
min,left;
printf
(
"please convert seconds into minutes and seconds.\n"
);
/*注意此处/n不可缺一部分,我忘记了n,只有/程序
就一直编译报错。*/
printf
(
"enter the number of the seconds(<=0 to quit):\n"
);
while
(sec<=1000)
{
sec=sec+100;
min=sec/SEC_PRE_MIN;
//得到分钟数;
left=sec%SEC_PRE_MIN;
//取模运算得到秒数;
printf
(
"%d seconds is %d minuts and %d seconds.\n"
,sec,min,left);
}
printf
(
"please stop convert!\n"
);
return
0;
}
|
运形结果:
3、
Profix前缀模式++i就完全等价于i=i+1;先加1后赋值。所以显而易见,i++就是先赋值后加1;--等同。
4、本章总结,用一个综合的例子来结尾,其中要注意的问题,就是程序一定要细心,不可犯低级错误,打错忘定义之类的!
实例程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
//综合示例程序:running.c
#include<stdio.h>
#define S_PER_M 60//每分钟的秒数
const
int
S_PER_H =3600;
//每小时的秒数
const
double
M_PER_K =0.62137;
//每公里的英里数
int
main(
void
)
{
double
distk,distm;
//分别以公里和英里记得跑过的距离
double
rate;
//以英里每小时位单位的平均速度
int
min,sec;
//跑步时用的分钟数和秒数
double
mtime;
//跑完一英里所用的时间以秒记
int
mmin,msec,
time
;
//跑完一英里所用的时间,以分钟、秒记
printf
(
"this program converts your time for a metric race\n"
);
printf
(
"to a time for running a mile and to your average\n"
);
printf
(
"speed in miles per hour.\n"
);
printf
(
"please enter the kilometers, the distance run .\n"
);
scanf
(
"%lf"
,&distk);
//lf表示读取一个double 类型的数值
printf
(
"Next enter your time in minuts and seconds.\n"
);
printf
(
"begin by entering the minutes.\n"
);
scanf
(
"%d"
,&min);
printf
(
"now enter the seconds. \n"
);
scanf
(
"%d"
,&sec);
time
=S_PER_M*min+sec;
//把时间转换为全部用秒表示
distm=M_PER_K*distk;
//把公里转化为英里,
rate=distm/
time
*S_PER_H;
//时间/距离=跑完每英里的用时
mtime=(
double
)
time
/distm;
mmin=(
int
)mtime/S_PER_M;
msec=(
int
)mtime%S_PER_M;
printf
(
"you ran %1.2f km (%1.2f miles)in %d min,%d sec.\n"
,distk,distm,min,sec);
printf
(
"that pace corresponds to running a mile in %d min,"
,mmin);
printf
(
"%d sec.\n your average speed was %1.2f mph.\n"
,msec,rate);
return
0;
}
|
运行结果如下:
本文转自 lillian_trip 51CTO博客,原文链接:http://blog.51cto.com/xiaoqiaoya/1951931,如需转载请自行联系原作者