天天看點

《c primer plus》 2.12程式設計練習

1.編寫一個程式,調用一次printf()函數,把你的姓名列印在一行。再調用一次printf()函數,把你的姓名分别列印在兩行。

    然後,再調用兩次printf()函數,把你的姓名列印在一行,輸出應如下所示:

    Guestav Mahler    第1次列印的内容

    Guestav                第2次列印的内容

    Mahler                  仍是第2次列印的内容

    Guestav Mahler    第3次和第4次列印的内容

#include<stdio.h>

int main(void) 
{
	printf("Ccc Hhh\n");
	printf("Ccc\nHhh\n");
	printf("Ccc ");
	printf("Hhh\n");
	getchar();
}
           

2.編寫一個程式,列印你的姓名和位址

#include<stdio.h>
int main(void)
{
	printf("CHh\n");
	printf("***************");
	getchar();
           

3.編寫一個程式把你的年齡轉換為天數,并顯示這兩個值。這裡不用考慮閏年的問題。

#include<stdio.h>
int main(void)
{
	//定義變量
	int age;
	int day;

	age = 23;
	day = age * 365;

	printf("day:%d\n", day);
	getchar();
}
           

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);
void deny(void);

int main(void)
{
	jolly();
	jolly();
	jolly();
	deny();
	getchar();
}

void jolly(void)
{
	printf("For he's a jolly good fellow!\n");
}

void deny(void)
{
	printf("Which nobody can deny!\n");
}
           

5.編寫一個程式,生成一下輸出:

    Brazil,Russia,India,China

    India,China,

    Brazil,Russia

    除了main()以外,該程式還要調用兩個自定義函數:一個名為br(),調用一次列印一次“Brazil,Russia”;

    另一個名為ic(),調用一次列印以西“India,China”。其他内容在main()函數中完成

#include<stdio.h>

void br(void);
void ic(void);

int main(void)
{
	br();
	printf(",");
	ic();
	printf("\n");
	ic();
	printf(",\n");
	br();
	printf("\n");
	getchar();
}

void br(void)
{
	printf("Brazil,Russia");
}

void ic(void)
{
	printf("India,China");
}
           

6.編寫一個程式,建立一個整型變量toes,并将toes設定為10。程式中還要計算toes的兩倍和toes的平方。

    該程式應列印3個值,并分别描述以示區分。

#include<stdio.h>

int main(void) {
	int toes;
	int d_toes;
	int s_toes;

	toes = 10;
	d_toes = toes * 2;
	s_toes = toes * toes;

	printf("toes:%d\n", toes);
	printf("toes的兩倍:%d\n", d_toes);
	printf("toes的平方:%d\n", s_toes);
	getchar();
}
           

7.許多研究表明,微笑益處多多。編寫一個程式,生成一下格式的輸出:

    Smile!Smile!Smile!

    Smile!Smile!

    Smile!

    該程式要定義一個函數,該函數被調用一次列印一次“Smile!”,根據程式的需要使用該函數。

#include<stdio.h>

void smile(void);

int main(void)
{
	smile();
	smile();
	smile();
	printf("\n");
	smile();
	smile();
	printf("\n");
	smile();
	printf("\n");
	getchar();
}

void smile(void)
{
	printf("Smile!");
}
           

    8.在C語言中,函數可以調用另一個函數。編寫一個程式,調用一個名為one_three()的函數,

    該函數在一行列印單詞“one”,再調用第2個函數two(),然後在另一行列印單詞“three”,two()函數在一行顯示單詞“two”。

    main()函數在調用one_three()函數前要列印短語“starting now:”,并在調用完畢後顯示短語“done!”。是以,該程式的輸出應如下所示:

    Starting now:

    one

    two

    three

    done!

#include<stdio.h>

void one_three(void);
void two(void);

int main(void)
{
	printf("starting now:\n");
	one_three();
	printf("\ndone!");
	getchar();
}

void one_three(void)
{
	printf("one\n");
	two();
	printf("\nthree");
}

void two(void)
{
	printf("two");
}