目录
基本数据类型
char 字符------一个字节
short 短整型
long 长整型
double 双精度浮点型
while循环语句
cpp
while (fahr < upper){
...
}
printf函数
cpp
printf((" %3d %6d\n", fahr, celsius);
// fahr占3个数字宽
// celsius占6个数字宽
/* 格式说明
%d 按照十进制整型数打印
%6d 按照十进制整型数打印,至少6个字符宽
%f 按照浮点数打印
%6f 按照浮点数打印,至少6个字符宽
%.2f 按照浮点数打印,小数点后有两位小数
%6.2f 按照浮点数打印,至少6个字符宽,小数点后有两位小数
此外,printf函数支持下列格式
%o 八进制
%x 十六进制
%c 字符
%s 字符串
%% 百分号本身
*/
赋值语句
cpp
fahr = lower;
for语句
cpp
#include <stdio.h>
main() {
int fahr;
for(fahr=0;fahr<=300;fahr=fahr+20){
printf("%3d %6.1f\n",fahr,(5.0/9.0)*(fahr-32));
}
}
/*
第1部分:初始化部分
第2部分:循环测试部分
第3部分:执行部分
*/
符号变量
#define指令可以把符号名(或称为符号常量)定义为一个特定的字符串
cpp
#define 名字 替换文本
// 比如
#define LOWER 0
#define UPPER 300
#define STEP 20
字符输入/输出
标准库提供了一次读/写一个字符的函数,其中最简单的是 getchar 和 putchar 两个
函数。每次调用时, getchar 函数从文本流中读入下一个输入字符,并将其作为结果值返回。
也就是说,在执行语句
cpp
// 从文本流中读入下一个输入字符
c = getchar()
// 将把整型变量 c 的内容以字符的形式打印出来
putchar()
后,变量c将包含输入流中的下一个字符,这种字符通常是通过键盘输入的。
数组
cpp
#include <stdio.h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}
该程序的声明语句int ndigit[10]将变量ndigit声明为由10个整型数构成的数组。在C语言中,数组下表总是从0开始,因此10个元素为ndgit[0], ndigit[1],...ndigit[9]。
if...else语句
cpp
if (条件 1)
语句 1
else if (条件 1)
语句 2
...
...
else
语句 n
函数
在C语言中可以简单、方便、高效地使用函数。我们经常会看到在定义后仅调用了一次的短函数,这样做可以使代码段更清晰易读。下面编写一个求幂的函数power(m,n)来说明函数定义的方法。
cpp
#include<stdio.h>
int power(int m,int n);
/* test power function */
main{
int i;
for(i=0;i<10;++i)
fprintf("%d %d %d\n",i,power(2,i),power(-3.i));
return 0;
};
/* power: raise base to n-th power; n >= 0 */
int power(int base, int n)
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}
/*
函数定义的一般形式:
返回值类型 函数名(0个或多个参数声明){
声明部分
语句序列
}
*/
函数定义中圆括号内出现的变量为形参(形式参数 ),而把函数调用中与形 式参数对应的值称为**实际参数。**power 函数计算所得的结果通过 return 语句返回给 main 函数。关键字 return 的后
面可以跟任何表达式,形式为:
return 表达式;
函数不一定有返回值。
在 C 语言的最初定义中,可以在程序的开头按照下面这种形式声明 power 函数:
int power();