編程練習(xí):
1.通過實驗編寫帶有此類問題的程序,觀察系統(tǒng)如何處理整數(shù)上溢,浮點數(shù)上溢,和浮點數(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),
有符號整數(shù)溢出屬未定義行為An example of undefined behavior is the behavior on integer overflow。
無符號整數(shù)overflows or out-of-bounds results silently wrap,我理解是“默默循環(huán)”。即4294967295之后從0開始循環(huán)。
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.發(fā)出一聲警報,打印下面文本:
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.編寫一個程序,讀取一個浮點數(shù),先打印成小數(shù)點形式,在打印成指數(shù)形式。然后,如果系統(tǒng)支持,再打印成p計數(shù)法,及十六進(jìn)制計數(shù)法。
按以下格式輸出(實際顯示的指數(shù)位數(shù)因系統(tǒng)而異):
float aNumber ;
scanf("%f",&aNumber);
printf("先打印成小數(shù)點形式: %f\n",aNumber);
printf("再打印成指數(shù)點形式: %e\n",aNumber);
printf("p計數(shù)法形式: %a\n",aNumber);
5.一年大約有3.156*10的七次方秒,編寫一個程序,提示用戶輸入年齡,然后顯示該年齡對應(yīng)的秒數(shù)。
double seconds = 3.156e7;
unsigned age;
printf("輸入年齡:");
scanf("%d",&age);
printf("這個年齡對應(yīng)的秒數(shù)是:%f",age * seconds);
6.一個水分子的質(zhì)量約為3.0*10的-23次方克,1夸脫水大約是950克。編寫一個程序,輸入夸脫數(shù),顯示水分子的數(shù)量。
#define QuarsWaterMolecules 950
unsigned weight;
printf("輸入夸脫數(shù):");
scanf("%ud",&weight);
printf("水分子數(shù)量:%ul",weight * QuarsWaterMolecules);
7. 一英寸相當(dāng)于2.54厘米,編寫一個程序,提示用戶輸入身高(/英寸),然后已厘米為單位顯示身高。
#define InchToCM 2.54
float height;
printf("輸入身高:\n");
scanf("%f",&height);
printf("這個身高換成厘米:%f",height * InchToCM);
8.在美國的體積測量系統(tǒng)中,1品脫等于2杯,1杯等于8盎司,1盎司等于2大湯勺,1大湯勺等于3茶勺。
編寫一個程序,提示用戶輸入杯數(shù),并以品脫,盎司,湯勺,茶勺為單位顯示等價容量。
#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);