《C Primer Plus》第2章 复习题与编程练习
复习题
1. C语言的基本模块是什么?
函数。
2. 什么是语法错误?
语法错误违反了组成语句或程序的规则。
3. 什么是语义错误?
含义错误。
4. 程序修改
正确的代码如下:
// week_in_a_year.c
#include <stdio.h>
#include <stdlib.h>
int main(void) /* 该程序打印一年有多少周*/
{
int s;
s=56;
printf("There are %d weeks in a year.\n",s);
system("pause");
return 0;
}
结果:

5. 程序打印什么内容?
6. 在main、int、function、char、=中,哪些是C语言的关键字?
int、char。
7. 输出变量words和lines的值
printf("There were %d words and %d lines.",words,lines);
8. 程序的状态
第7行:a=5, b=2
第8行:a=5, b=5
第9行:a=5, b=5
9. 程序的状态
第7行:x=10, y=5
第8行:x=10, y=15
第9行:x=150,y=15
编程练习
1. 打印姓名
程序:
// practice2_12_1.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("Gustav Mahler\n");
printf("Gustav\nMahler\n");
printf("Gustav ");
printf("Mahler\n");
system("pause");
return 0;
}
结果:

2. 打印姓名和地址
程序:
// practice2_12_2.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[10]="xiye";
char address[20]="UESTC";
printf("My name is %s, my address is %s.\n", name, address);
system("pause");
return 0;
}
结果:

3. 年龄转换为天数
程序:
// practice2_12_3.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int year;
int day;
year = 22;
day = 365 * year;
printf("I am %d years old, which equals to %d days.\n", year, day);
system("pause");
return 0;
}
结果:

4. 打印内容
程序:
// practice2_12_4.c
#include <stdio.h>
#include <stdlib.h>
void jolly(void);
void deny(void);
int main(void)
{
for(int i=0;i<3;i++) jolly();
deny();
system("pause");
return 0;
}
void jolly(void)
{
printf("For he's a jolly good fellow!\n");
}
void deny(void)
{
printf("Which nobody can deny!\n");
}
结果:
5. 打印内容
程序:
// practice2_12_5.c
#include <stdio.h>
#include <stdlib.h>
void br(void);
void ic(void);
int main(void)
{
br();
printf(", India, China\n");
ic();
printf(",\nBrazil, Russia\n");
system("pause");
return 0;
}
void br(void)
{
printf("Brazil, Russia");
}
void ic(void)
{
printf("India, China");
}
结果:

6. 打印值
程序:
// practice2_12_6.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int toes;
toes = 10;
printf("toes=%d, 2*toes=%d, toes^2=%d\n", toes, 2 * toes, toes * toes);
system("pause");
return 0;
}
结果:

7. 打印Smile!
程序:
// practice2_12_7.c
#include <stdio.h>
#include <stdlib.h>
void smile(void);
int main(void)
{
smile();
smile();
smile();
printf("\n");
smile();
smile();
printf("\n");
smile();
printf("\n");
system("pause");
return 0;
}
void smile(void)
{
printf("Smile!");
}
结果:

8. 函数调用
程序:
// practice2_12_8.c
#include <stdio.h>
#include <stdlib.h>
void one(void);
void two(void);
int main(void)
{
printf("starting now:\n");
one();
two();
printf("three\ndone!\n");
system("pause");
return 0;
}
void one(void)
{
printf("one\n");
}
void two(void)
{
printf("two\n");
}
结果:

这篇博客回顾了C语言的基本模块——函数,并讲解了语法错误和语义错误的区别。通过一系列程序修改和打印练习,展示了C语言的变量使用、程序状态及控制流程。还包含了年龄转换为天数等实际编程问题的解决示例。
934

被折叠的 条评论
为什么被折叠?



