版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
为使用《C Primer Plus》学习C的初学者准备的。
- 编写一个程序,调用一次printf()函数,把你的姓名打印在一行。再调用一次printf()函数,把你的姓名分别打印在两行。然后,再调用两次printf()函数,把你的姓名打印在一行。输出应该如下图所示。
#include <stdio.h>
int main(int argc, char const **argv) {
/*调用一次printf函数,把名字打印在一行 \n是换行,也就是从另一行输出*/
printf("Gustav Mahler\n");
/*调用一次printf函数,把你的名字打印在两行*/
printf("Gustav\nMahler\n");
/*调用两次printf函数 把名字打印在一行 第二个printf输出的内容紧挨着第一行输出*/
printf("Gustav ");
printf("Mahler");
return 0;
}
- 编写一个程序,打印你的姓名和地址。
#include <stdio.h>
int main(int argc, char const **argv) {
/*打印地址和姓名*/
printf("My name is Xinghai Liao, from Changsha, China.");
return 0;
}
- 编写一个程序把你的年龄转换为天数,并显示这两个值。这里不用考虑闰年的问题。
#include <stdio.h>
//函数声明
int ageConvertDay(int age);
int main(int argc, char const **argv) {
int age;
//输入年龄
printf("Please enter your age:");
scanf("%d", &age);
//ageConvertDay函数计算结果
int result = ageConvertDay(age);
//输出结果
printf("Your age is %d, the result is %d.", age, result);
return 0;
}
/*不考虑闰年计算年龄的函数定义*/
int ageConvertDay(int age) {
return age*365;
}
- 编写一个程序,生成一下输出。除了main函数以外,该程序还要调用两个自定义函数:一个名为jolly(),用于打印前3条消息,调用一次打印一条;另外一个函数名为deny(),打印最后一条消息。
#include <stdio.h>
/*函数声明*/
void jolly();
void deny();
int main(int argc, char const **argv) {
/*调用三次jolly*/
jolly();
jolly();
jolly();
/*调用deny*/
deny();
}
/*函数定义*/
void jolly() {
printf("For he's a jolly good fellow!\n");
}
void deny() {
printf("Which nobody can deny!\n");
}
- 编写一个程序,生成以下输出。
#include <stdio.h>
/*函数声明*/
void br(void);
void ic(void);
int main(int argc, char const **argv) {
/*打印第一句话*/
br();
printf(", ");//输出逗号
ic();
printf("\n");//输出换行
/*打印第二句话*/
ic();
printf(", \n");//输出逗号和换行
/*打印第三句话*/
br();
}
/*函数定义*/
void br(void) {
printf("Brazil, Russia");
}
void ic(void) {
printf("India, China");
}
- 编写一个程序,创建一个整型变量toes,并将toes设置为10。程序中还要计算toes的两倍和toes的平方。该程序应打印三个值,并分别描述以示区分。
#include <stdio.h>
int main(int argc, char const **argv) {
/*声明整型变量toes*/
int toes;
/*给toes变量赋值10*/
toes = 10;
/*计算toes的两倍 并赋值给doubleToes*/
int doubleToes = toes * 2;
/*计算toes的平方 并赋值给squareToes*/
int squareToes = toes * toes;
/*输出*/
printf("toes:%d doubleToes:%d squareToes:%d", toes, doubleToes, squareToes);
return 0;
}
- 编写一个程序,生成以下格式的输出:
#include <stdio.h>
int main(int argc, char const **argv) {
printf("Smile!Smile!Smile!\n");
printf("Smile!Smile!\n");
printf("Smile!");
return 0;
}
- 编写一个程序,调用一个名为one_three()的函数。该函数在第一行打印单词"one",再调用第二个函数two(),然后在另一行打印单词"Three"。two()函数在一行显示单词"two"。main()函数在调用one_three()函数前要打印"starting now:",并在调用完毕后打印"done!"。输出应该如下。
#include <stdio.h>
/*声明函数*/
void two();
void one_three();
int main(int argc, char const **argv) {
printf("starting now:\n");
one_three();
printf("done!");
}
/*定义函数*/
void two() {
printf("two\n");
}
void one_three() {
printf("one\n");
two();//在这个函数调用two()函数 有些老的编译器声明时不把two()函数放在前面声明可能会报错
printf("three\n");
}