C primer plus 第六版 第6版 003章 第三章 編程 練習 答案 中文

編程練習:

1.通過實驗編寫帶有此類問題的程序,觀察系統如何處理整數上溢,浮點數上溢,和浮點數下移的情況?

整數上溢:

int i = 2147483647;

unsigned int j = 4294967295;

printf("%d %d %d\n", i, i+1, i+2);

printf("%u %u %u\n", j, j+1, j+2);

剛翻了下C99標準,

有符號整數溢出屬未定義行為An example of undefined behavior is the behavior on integer overflow。

無符號整數overflows or out-of-bounds results silently wrap,我理解是“默默循環”。即4294967295之后從0開始循環。

2.編寫一個程序,要求提示輸入一個ASCII碼值,如66,然后打印輸入字符。

/* charcode.c-displays code number for a character */

#include

int main(void)

{

char ch;

printf("Please enter a character.\n");

scanf("%c", &ch);? ?/* user inputs character */

printf("The code for %c is %d.\n", ch, ch);

return 0;

}

Please enter a character.

m

The code for m is 109.

Program ended with exit code: 0

3.發出一聲警報,打印下面文本:

Startled by the sudden sound,Sally shouted,

"By the Great Pumpkin,what was that!"

printf("%c",'\a');

printf("Startled by the sudden sound,Sally shouted,\n");

printf("\"By the Great Pumpkin,what was that!\"\n");

我用XCode寫的代碼,表示并沒有聽到警報聲音。

4.編寫一個程序,讀取一個浮點數,先打印成小數點形式,在打印成指數形式。然后,如果系統支持,再打印成p計數法,及十六進制計數法。

按以下格式輸出(實際顯示的指數位數因系統而異):

float aNumber ;

scanf("%f",&aNumber);

printf("先打印成小數點形式: %f\n",aNumber);

printf("再打印成指數點形式: %e\n",aNumber);

printf("p計數法形式: %a\n",aNumber);

5.一年大約有3.156*10的七次方秒,編寫一個程序,提示用戶輸入年齡,然后顯示該年齡對應的秒數。

double seconds = 3.156e7;

unsigned age;

printf("輸入年齡:");

scanf("%d",&age);

printf("這個年齡對應的秒數是:%f",age * seconds);

6.一個水分子的質量約為3.0*10的-23次方克,1夸脫水大約是950克。編寫一個程序,輸入夸脫數,顯示水分子的數量。

#define QuarsWaterMolecules 950

unsigned weight;

printf("輸入夸脫數:");

scanf("%ud",&weight);

printf("水分子數量:%ul",weight * QuarsWaterMolecules);

7. 一英寸相當于2.54厘米,編寫一個程序,提示用戶輸入身高(/英寸),然后已厘米為單位顯示身高。

#define InchToCM 2.54

float height;

printf("輸入身高:\n");

scanf("%f",&height);

printf("這個身高換成厘米:%f",height * InchToCM);

8.在美國的體積測量系統中,1品脫等于2杯,1杯等于8盎司,1盎司等于2大湯勺,1大湯勺等于3茶勺。

編寫一個程序,提示用戶輸入杯數,并以品脫,盎司,湯勺,茶勺為單位顯示等價容量。

#define KPintToCup 2

#define KCupToOunce 8

#define OunceToSoupLadle 2

#define SoupLadleToTeaLadle 3

printf("輸入杯數:");

unsigned int cups;

scanf("%ud\n",&cups);

printf("品脫:%d\n",cups * KPintToCup);

printf("盎司:%d\n",cups * KPintToCup * KCupToOunce);

printf("湯勺:%d\n",cups * KPintToCup * KCupToOunce * OunceToSoupLadle);

printf("茶勺:%d\n",cups * KPintToCup * KCupToOunce * OunceToSoupLadle * SoupLadleToTeaLadle);

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容