My “The C Programing Language” Learning
一、 Hello, world
第一个c程序
#include <stdio.h> //包含标准库的信息
main() //定义名为main的函数,它不接受参数值
//main函数的语句都被括在花括号中
{
printf("hello, world\n"); //main函数调用库函数printf以显示
//字符序列,\n代表换行符
}
二、华氏温度、摄氏温度的转换
1.课本代码
#include <stdio.h>
/* 当fahr=0,20,···,300是,分别打
印华氏温度和摄氏温度对照表*/
int main()
{
int fahr, celsius;
int lower, upper, step;
lower = 0; //温度表的下限
upper = 300; //温度表的上限
step = 20; // 步长
fahr = lower;
while (fahr <= upper)
{
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f %10.1f\n", fahr, celsius);
fahr = fahr + step;
}
return 0;
}
2.我的代码
#include <stdio.h>
int main()
{
int f = 0, c = 0;
for(int i = 0; i < 16; i++)
{
c = ((f - 32) * 5 ) / 9; // 缺点:嵌套过多不易阅读
//*5写在前减少括号嵌套读
f = f + 20;
printf("%d ", c);
printf("\n");
}
return 0;
}
三、输入复制到输出
#include <stdio.h>
/*将输入复制到输出*/
int main()
{
int c;
while ((c = getchar()) != EOF){
putchar(c);
}
}
四、统计字数和行数
1.统计字数
#include <stdio.h>
/* 统计输入的字符数 */
int main()
{
double nc;
for (nc = 0; getchar() != EOF; ++nc){
;
}
printf("%.0f\n", nc);
return 0;
}
2. 统计行数
课本代码
#include <stdio.h>
/*统计输入中的行数*/
int main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n'){
++nl;
}
}
printf("%d\n", nl);
return 0;
}
我的代码 (错误Error)
#include <stdio.h>
/*统计输入中的行数*/
int main()
{
int nc = 0;
while (getchar != EOF){
for ( ; getchar() == '\n'; ++nc){ //错误:while中getchar得到的字符未传递过来
; //在此处重复要求getchar输入字符
}
}
printf("%d\n", nc);
return 0;
}