編程練習(xí):
1.通過(guò)實(shí)驗(yàn)編寫(xiě)帶有此類(lèi)問(wèn)題的程序吨瞎,觀(guān)察系統(tǒng)如何處理整數(shù)上溢痹兜,浮點(diǎn)數(shù)上溢,和浮點(diǎn)數(shù)下移的情況关拒?
整數(shù)上溢:
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標(biāo)準(zhǔn)佃蚜,
有符號(hào)整數(shù)溢出屬未定義行為An example of undefined behavior is the behavior on integer overflow。
無(wú)符號(hào)整數(shù)overflows or out-of-bounds results silently wrap着绊,我理解是“默默循環(huán)”谐算。即4294967295之后從0開(kāi)始循環(huán)。
2.編寫(xiě)一個(gè)程序归露,要求提示輸入一個(gè)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.發(fā)出一聲警報(bào)恐锦,打印下面文本:
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寫(xiě)的代碼,表示并沒(méi)有聽(tīng)到警報(bào)聲音疆液。
4.編寫(xiě)一個(gè)程序一铅,讀取一個(gè)浮點(diǎn)數(shù),先打印成小數(shù)點(diǎn)形式堕油,在打印成指數(shù)形式潘飘。然后,如果系統(tǒng)支持掉缺,再打印成p計(jì)數(shù)法卜录,及十六進(jìn)制計(jì)數(shù)法。
按以下格式輸出(實(shí)際顯示的指數(shù)位數(shù)因系統(tǒng)而異):
float aNumber ;
scanf("%f",&aNumber);
printf("先打印成小數(shù)點(diǎn)形式: %f\n",aNumber);
printf("再打印成指數(shù)點(diǎn)形式: %e\n",aNumber);
printf("p計(jì)數(shù)法形式: %a\n",aNumber);
5.一年大約有3.156*10的七次方秒眶明,編寫(xiě)一個(gè)程序艰毒,提示用戶(hù)輸入年齡,然后顯示該年齡對(duì)應(yīng)的秒數(shù)搜囱。
double seconds = 3.156e7;
unsigned age;
printf("輸入年齡:");
scanf("%d",&age);
printf("這個(gè)年齡對(duì)應(yīng)的秒數(shù)是:%f",age * seconds);
6.一個(gè)水分子的質(zhì)量約為3.0*10的-23次方克丑瞧,1夸脫水大約是950克。編寫(xiě)一個(gè)程序犬辰,輸入夸脫數(shù)嗦篱,顯示水分子的數(shù)量。
#define QuarsWaterMolecules 950
unsigned weight;
printf("輸入夸脫數(shù):");
scanf("%ud",&weight);
printf("水分子數(shù)量:%ul",weight * QuarsWaterMolecules);
7. 一英寸相當(dāng)于2.54厘米幌缝,編寫(xiě)一個(gè)程序灸促,提示用戶(hù)輸入身高(/英寸),然后已厘米為單位顯示身高。
#define InchToCM 2.54
float height;
printf("輸入身高:\n");
scanf("%f",&height);
printf("這個(gè)身高換成厘米:%f",height * InchToCM);
8.在美國(guó)的體積測(cè)量系統(tǒng)中浴栽,1品脫等于2杯荒叼,1杯等于8盎司,1盎司等于2大湯勺典鸡,1大湯勺等于3茶勺被廓。
編寫(xiě)一個(gè)程序,提示用戶(hù)輸入杯數(shù)萝玷,并以品脫嫁乘,盎司,湯勺球碉,茶勺為單位顯示等價(jià)容量蜓斧。
#define KPintToCup 2
#define KCupToOunce 8
#define OunceToSoupLadle 2
#define SoupLadleToTeaLadle 3
printf("輸入杯數(shù):");
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);