C 程序设计语言第二版 第一章 习题
第一题
#include <stdio.h> int main(void){ printf("hello, world"); return 0; }
第二题
#include <stdio.h> int main(void){ printf("hello, world\c12"); return 0; }
会出现警告,并把c打印出来
第三题
#include <stdio.h> int main(void){ float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; printf("Fahrenheit Celsius\n"); while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%6.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } return 0; }
第四题
#include <stdio.h> int main(void){ float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; celsius = lower; printf("Celsius Fahrenheit\n"); while (celsius <= upper) { fahr = (9.0 / 5.0) * celsius + 32.0; printf("%6.0f %6.1f\n", celsius, fahr); celsius = celsius + step; } return 0; }
第五题
#include <stdio.h> int main(void){ float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; printf("Fahrenheit Celsius\n"); for (fahr = upper; fahr >=0; fahr = fahr - step) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%6.0f %6.1f\n", fahr, celsius); } return 0; }
第六题
未输入结束符为0,输入结束符为1
第七题
#include <stdio.h> int main(void){ int ch; while (1) { if ((ch = getchar()) == EOF){ printf("c = %d\n", ch); printf("EOF = %d\n", EOF); break; } } return 0; }
-1
第八题
#include <stdio.h> int main(void){ int space, tab, enter, ch; space = tab = enter = 0; while ((ch = getchar()) != EOF) { if (ch == ' ') { space++; }else if (ch == '\t'){ tab++; }else if (ch == '\n'){ enter++; } } printf("%d %d %d", space, tab, enter); return 0; }
第9题
#include <stdio.h> int main(void){ int is_space, ch; is_space = 0; while ((ch = getchar()) != EOF) { if (is_space == 0) { if (ch == ' ') { putchar(ch); is_space = 1; }else putchar(ch); }else{ if (ch != ' ') { putchar(ch); is_space = 0; } } } return 0; }
书中的答案更加精简,定义了前一个字符,判断前一个字符的内容实现
第十题
#include <stdio.h> int main(void){ int ch; while ((ch = getchar()) != EOF) { if (ch == '\t') { putchar('\\'); putchar('t'); }else if (ch == '\b'){ putchar('\\'); putchar('b'); }else if (ch == '\\'){ putchar('\\'); putchar('\\'); }else putchar(ch); } return 0; }
第十一题
边界测试
第十二题
#include <stdio.h> int main(void){ int ch, last; last = '\n'; while ((ch = getchar()) != EOF) { if ((ch == '\t' || ch == ' ' || ch == '\n') && last != '\n') { putchar('\n'); last = '\n'; }else if (ch == '\t' || ch == ' ' || ch == '\n'); else{ putchar(ch); last = ch; } } return 0; }