ubuntu的terminal运行:
- 编辑源文件 file.c
- (编译)cc file.c
- (生成可执行文件)生成a.out
- (运行)./a.out
//test_1
#include <stdio.h> //包含标准库信息
int main() //主函数,程序的起点
{
printf("hello,world\n"); //printf函数
return 0;
}
//test_2
//使用公式C=(5/9)×(F-32)打印华氏温度和摄氏温度的对照表
#include <stdio.h>
int main()
{
float F, C; //变量声明,变量必须先声明,后使用
float lower = 0, upper = 300, step = 20;
F = lower; //变量初始化
while ( F <= upper ) { //while循环语句
C = 5.0 * ( F - 32.0 )/9.0;
printf("%6.0f%10.2f\n", F, C);
F += step;
}
return 0;
}
printf输出格式说明:
%d 十进制整型输出
%6d 6个字符宽度的十进制整型输出
%f 浮点型输出
%6.2f 6个字符宽度的浮点型输出,其中包含2位小数
%c 字符输出
%s 字符串输出
%% %输出
//test_2-1
//使用公式C=(5/9)×(F-32)打印华氏温度和摄氏温度的对照表
#include <stdio.h>
int main()
{
for (float F=0; F<=300; F+=20) { //for循环语句
printf("%6.0f%10.2f\n", F, 5.0*(F-32.0)/9.0);
}
return 0;
}
magic number(幻数) 和 符号常量:
test_2-1 中的300,20等称为magic number,都不易读,且一旦修改,会十分繁琐。
#define UPPER 300
#define STEP 20
#define 名字 替换文本
其中的UPPER, STEP称为符号常量。增强代码的易读性,并且容易修改其值。