2022年1月25日 星期二

Lesson 2 Assignment(Suggested answer)

 

Lesson 2 Assignment

 

Assignment(1)

- Rewrite the following codes, use the constant “a” to replace the “2” in the

formula. The result should be the same.

以上作業要求使用常數變量a,取代程式中2的位置,即1x2應變成1*a

 

建議答案如下:

說明:

1. 要輸出數值(value)、算式結果或變數(varibale)的話,要使用以下格式:

        printf("%d%d",a,b)

        以上例子中" "內有兩個格式輸出,都是%d,代表都是整數值," "後按順序要有相同數目的數值、變量(variable)或算式值,上例中是ab

" " 後的數值、變量或算式值與前面" "內的格式數目不相同的,系統會根據電腦內記憶體位址內當時貯存的數值,自動輸出數值的,如下:

 

---------------------------------------------------------------------------------------------------

Assignment (2)

Try to calculate the area of a square. The output should be as follows: (use

constant to save the value of the length of the square)

The length of a square is: 5

The area of this square is: 5 x 5 = 25

留意,以上題目要求使用常數(constant variable)方式,貯存正方形(square)的長度(length),而正方形的面積(area)應是計算出來的。

建議答案如下:

說明:

1. 4: 設定一個常數(constant),名稱是a,數值是5

2. 5: 輸出正方形的長度。

3. 6行,輸出正方形的面積,注意,這裡有3個格式設定,都是%d,屬於整數。

4. 使用常數方式有一個好處,如果要更改以上正方形的長度的話,祇需要更改第4行,把const a=5; 中的 5 換成其他數值便可以。

------------------------------------------------------------------------------------------------------------

Assignment(3)

- Try to calculate the area of a triangle. The output should be as follows: (use

constant to save the value of the height and the base length of the triangle)

The height of the triangle is: 2

The base length of the triangle is: 4

The area of the triangle is: 4

這題目跟上一題差不多,要用常數(constant)貯存三角形(triangle)的高度(height)及底長(base length)

 

建議答案如下:

說明:

1. 三角形的面積是 X/2。因此第8行最後是h*b/2

 

備註: 不過以上程式有一問題,如高度(height)3,底長( base length)3的話,看看輸出結果是甚麼? 正確嗎? 正確應是4.5的。

沒有留言:

張貼留言

如何於C程式內輸入字串?

之前我們學過如何於 C 程式內輸入數目字,但如要輸入字串,例如姓名,又要如何處理呢 ?   跟其他大部分電腦程言不一樣, C 並沒有一個字串的變數數據類型 (variable data type) , C 是使用字元 (character) 及變數陣列 (array)...