第二章编程练习
1.编写一个程序,调用一次 printf()函数,把你的姓名打印在一行。再调 用一次 printf()函数,把你的姓名分别打印在两行。然后,再调用两次printf() 函数,把你的姓名打印在一行。输出应如下所示(当然要把示例的内容换成 你的姓名):
Gustav Mahler 第1次打印的内容
Gustav 第2次打印的内容
Mahler 第3次打印的内容
Gustav Mahler 第4次打印的内容
#include<stdio.h>
void br(void)
{
printf("Brazil,Russia,India,China\n");
}
void ic(void)
{
printf("India,China\n");
}
int main()
{
printf("Gustav Mahler\n");
printf("Gustav\nMahler\n");
printf("Gustav");
printf("Mahler\n");
getchar();
getchar();
return;
}
2.编写一个程序,打印你的姓名和地址。
#include<stdio.h>
int main()
{
char name[20];
char adress[40];
scanf("%s%s", name, adress);
printf("%s%s", name, adress);
getchar();
getchar();
return 0;
}
3.编写一个程序把你的年龄转换成天数,并显示这两个值。这里不用考 虑闰年的问题。
#include<stdio.h>
int main()
{
int olds;
int days;
scanf("%d", &olds);
days = olds * 365;
printf("I'm %d years old,%d days old",olds,days);
getchar();
getchar();
return 0;
}
4.编写一个程序,生成以下输出: For he’s a jolly good fellow! For he’s a jolly good fellow! For he’s a jolly good fellow! Which nobody can deny! 除了 main()函数以外,该程序还要调用两个自定义函数:一个名为
jolly(),用于打印前 3 条消息,调用一次打印一条;另一个函数名为 deny(),打印最后一条消息。
#include<stdio.h>
void jolly(void)
{
printf("For he's a jolly good fellow!\n");
printf("For he's a jolly good fellow!\n");
printf("For he's a jolly good fellow!\n");
}
void deny(void)
{
printf("Which nobody can deny!");
}
int main()
{
jolly();
deny();
system("pause");
return 0;
}
5.编写一个程序,生成以下输出: Brazil, Russia, India, China India, China, Brazil, Russia 除了main()以外,该程序还要调用两个自定义函数:一个名为br(),调 用一次打印一次“Brazil, Russia”;另一个名为ic(),调用一次打印一次“India, China”。其他内容在main()函数中完成。
#include<stdio.h>
int main()
{
br();
ic();
printf("Brazil,Russia\n");
getchar();
getchar();
return 0;
}
6.编写一个程序,创建一个整型变量toes,并将toes设置为10。程序中还 要计算toes的两倍和toes的平方。该程序应打印3个值,并分别描述以示区 分。
#include<stdio.h>
int main()
{
int toes,toes2,toes3;
toes = 10;
toes2 = toes*toes;
toes3 = toes*toes*toes;
printf("%d\t%d\t%d\t", toes, toes2, toes3);
system("pause");
return 0;
}
7.许多研究表明,微笑益处多多。编写一个程序,生成以下格式的输 出:
Smile!Smile!Smile!
Smile!Smile!
Smile!
该程序要定义一个函数,该函数被调用一次打印一次“Smile!”,根据程 序的需要使用该函数。
#include<stdio.h>
void smile()
{
printf("smile!");
}
int main()
{
smile();
smile();
smile();
printf("\n");
smile();
smile();
printf("\n");
smile();
system("pause");
return 0;
}
```
8.在C语言中,函数可以调用另一个函数。编写一个程序,调用一个名 为one_three()的函数。该函数在一行打印单词“one”,再调用第2个函数 two(),然后在另一行打印单词“three”。two()函数在一行显示单词“two”。 main()函数在调用 one_three()函数前要打印短语“starting now:”,并在调用完毕后显示短语“done!”。因此,该程序的输出应如下所示:
starting now:
one
two
three
done!
```c
#include<stdio.h>
void one_three()
{
printf("one\n\n");
}
void two()
{
printf("three\n\n");
}
int main()
{
printf("starting now:\n\n");
one_three();
printf("two\n\n");
two();
printf("done\n");
system("pause");
return 0;
}