1-1_hello.c
#include
main()
{
printf("Hello,world!");
}
1-2_fahr.c
华氏温度和设施温度的转换
#include
main()
{
int fahr,celsius;
int lower,upper,step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper){
celsius = 5 * (fahr-32)/9;
printf("%d\t%d\n",fahr,celsius);
fahr = fahr + step;
}
}
执行结果:
$ ./1-2_fahr.exe
0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148
1-4_count.c
单词计数
#include
#define IN 1
#define OUT 0
main()
{
int c,nl,nw,nc,state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF){
++nc;
if (c == '\n')
++nl;
if (c ==' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT){
state = IN;
++nw;
}
}
printf("%d %d %d\n",nl,nw,nc);
}
1-9_lines.c
查找最长的行,并打印出来:
#include
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print the longest input line */
main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getline(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
阅读(26362) | 评论(0) | 转发(1) |