C Primer Plus 第三章 編程練習

 

1.經過試驗(即編寫帶有此類問題的程序)觀察系統如何處理整數上溢、浮點數上溢和浮點數下溢的狀況。spa

#include<stdio.h>

int main(void) { unsigned int a = 4294967295; float b = 3.4e38; float c = b*10; float d = 0.1234e-2; printf("a=%u a+1=%u\n",a,a+1); printf("b=%e c=%e\n",b,c); printf("d=%f d/10=%f\n",d,d/10); return 0; }

運行結果:3d

2.編寫一個程序,要求提示輸入一個ASCII碼值(如,66),而後打印輸入字符。code

#include<stdio.h>

int main(void) { char a; printf("請輸入一個ASCII碼值:"); scanf("%d",&a); printf("%c\n",a); return 0; }

運行結果:blog

3.編寫一個程序,發出一聲警報,而後打印下面的文本:input

Startled by the sudden sound,Sally shouted,io

「By the Great Pumpkin,what was that!」class

#include<stdio.h>
int main(void) { printf("\aStartled by the sudden sound, Sally shouted,\n"); printf("\"By the Great Pumpkin,what was that!\"\n"); return 0; }

運行結果:float

4. 編寫一個程序,讀取一個浮點數,先打印成小數點形式,再打印成指數形式。而後,若是系統支持,在打印成p計數法(即十六進制計數法)形式。gc

Enter a floating-point value :64.25程序

fixed-point notation:64.250000

exponential notation:6.425000e+01

p notation:0x1.01p+6

#include<stdio.h>
int main(void) { float i; printf("Enter a floating-point value :"); scanf("%f",&i); printf("fixed-point notation:%f\n",i); printf("exponential notation:%e\n",i); printf("p notation:%a\n",i); return 0; }

運行結果:

5. 一年大約有3.156X107秒,編寫一個程序,提示用戶輸入年齡,而後顯示該年齡對應的秒數。

#include<stdio.h>
int main(void) { double seconds = 3.156e7; unsigned age; printf("請輸入年齡:"); scanf("%d",&age); printf("該年齡對應的秒數是:%f\n",age * seconds); return 0; }

運行結果:

6. 一個水分子的質量約爲3.0X1023克,1夸脫水大約是950克。編寫一個程序,提示用戶輸入水的夸脫數,並顯示水分子的數量。

#include <stdio.h>

#define WATER 3.0e-23  //1個水分子的質量
#define DEHYDRATION 950  //1夸脫水的質量

int main(int argc, char *argv[]) { float i, total; //total表示水分子的數量
        printf("please input:"); scanf("%f", &i); total = i * DEHYDRATION / WATER; printf("%e\n", total); return 0; }

運行結果:

7.1英寸至關於2.54釐米。編寫一個程序,提示用戶輸入升高(/英寸),而後以釐米爲單位顯示升高。

#include<stdio.h>

#define INCH 2.54

int main(void) { float i,height; printf("請輸入身高(英寸):"); scanf("%f",&i); height = i*INCH; printf("height = %f\n",height); return 0; }

運行結果:

8.在美國的體積測量系統中,1品脫等於2杯,1杯等於8中盎司,1盎司等於2答湯匙,1大湯匙等於3茶勺。編寫一個程序,提示用戶輸入杯數,並以品脫、盎司、湯匙、茶勺爲單位顯示等價容量。思考對於該程序,爲什麼使用浮點類型比整數類型更合適?

#include <stdio.h> #include <stdlib.h>
 
int main() { float cup, pint, ounce, spoon, teaspoon; printf("請輸入杯數:"); scanf("%f", &cup); pint = cup / 2; ounce = 8 * cup; spoon = 8 * cup * 2; teaspoon = 8 * cup * 2 * 3; printf("品脫:%f 盎司:%f 湯匙:%f 茶勺:%f\n", pint, ounce, spoon, teaspoon); return 0; }

運行結果:

若是用pint用整數類型的話,若杯數是6.5杯,那麼pint就會捨去小數位的數字,所以浮點類型比整數類型更合適。

不妥之處歡迎批評指正,謝謝你們!

相關文章
相關標籤/搜索