第2章 C语言概述
复习题
1、如何称呼C程序的基本模块?
答:它们被称为函数。
2、什么是语法错误?给出它的一个英语例子和C语言例子。
答:C的语法错误是指把正确的C符号放在了错误的位置。这是英语中的一个例子:"Me speak English good.";这是C语言的一个例子:
printf "Where are the parentheses?";
3、什么是语义错误?给出它的一个英语例子和C语言例子。
答:语义错误就是在意思上的错误。这是英语中的一个例子:"The sentence is excellent Italian.";这是C语言中的一个例子:
thrice_n = 3 + n;
4、Indiana Sloth 已经编好了下面的程序,并想征求你的意见。请帮助他评定。
1 include studio.h
2 int main{void} /*该程序可显示出一年中有多少周/*
3 (
4 int s
5
6 s: = 56;
7 print(There are s weeks in a year.);
8 return 0;
答:第1行:以一个#开始,拼写出文件名stdio.h,然后把文件名放在一对尖括号中。
第2行:使用(),而不是使用{};使用*/来结束注释,而不是使用/*。
第3行:使用{,而不是(。
第4行:使用分号来结束语句。
第5行:Indiana使这一行(空白行)正确!
第6行:使用=,而不是使用:=进行赋值(显然,Indiana 了解一些Pascal)。每年有52周而不是56周。
第7行:应该是
printf("There are %d weeks in a year.\n",s); 第9行:源程序没有第9行,但是应该有,它应该包含一个结束花括号}。
在进行这些修改之后,代码如下:
1 #include<stdio.h>
2 int main(void) /*该程序可显示出一年中有多少周/*
3 {
4 int s;
5
6 s = 52;
7 printf("There are %d weeks in a year.\n",s);
8 return 0;
9 }
5、假设下面的每一个例子都是某个完整程序的一部分,它们每个将输出什么结果?
a.printf("Baa Baa Black Sheep.");
printf("Have you any wool?\n");
b.printf("Begone!\n0 creature of lard!");
c.printf("What?\nNo/nBonzo?\n");
d.int num;
num = 2;
printf("%d + %d = %d",num,num,num + num);
答:a.Baa Baa Black Sheep.Have you any wool?(注意:在句号之后没有空格。)
b.Begone!
0 creature of lard!(注意光标仍留在第2行结束处。)
c.What?
No/nBonzo?(注意斜线符号”/“没有反斜线符号”\“所具有的作用,它只是简单地作为斜线符号被打印出来。)
d.2 + 2 = 4
6、下面哪几个是C的关键字?main,int,function,char,=
答:int,char(注意
main只是一个函数名,函数是C中的一个技术术语。=是一个运算符)
7、如何以下面的格式输出words和lines的值:"There were 3020 words and 350 lines"?这里,3020和350代表两个变量的值。
答:
1 #include <stdio.h>
2 int main(void)
3 {
4 int num1,num2;
5 num1 = 3020;
6 num2 = 350;
7
8 printf("There were %d words and %d lines\n",num1,num2);
9 return 0;
10 }
8、考虑下面的程序:
1 #include <stdio.h>
2 int main(void)
3 {
4 int a, b;
5
6 a = 5;
7 b = 2; /*第7行*/
8 b = a; /*第8行*/
9 a = b; /*第9行*/
10 printf("%d %d\n", b, a);
11 return 0;
12 }
请问在第7行、第8行和第9行之后程序的状态分别是什么?
答:第7行之后,a为5,b为2。第8行之后,a为5,b为5。第9行之后,a为5,b为5。
编程练习1、