--- tags: CSE --- # HW1 ## 題目說明 Objective : Learning how to use function like printf or scanf and some computation in C. ### 1.1 Write a program to calculate the area of a triangle (Hint : please declare float) Input : 5 3 Output : ![](https://i.imgur.com/cvlyQwz.png =50%x) ### 1.2 Write a program to implement the following equation step by step [𝑎 + 𝑏 × (𝑎 − 𝑏)] ÷ 𝑏 a. Print (a-b) = ? b. Print b*(a-b) = ? c. Print a+b*(a-b) = ? d. Print [a+b*(a-b)]/b = ? Input : 3 9 Output: ![](https://i.imgur.com/qSlf9WT.png =50%x) ## 程式碼 **1.1** ```c= #include <stdio.h> ``` ↑ 一開始要include函式庫 ```c=2 float base, height; ``` ↑ 宣告兩個單精度浮點數變數 ```c=3 printf("請輸入三角形的底邊長度 : "); scanf("%f", &base); ``` 根據題意用printf在視窗上顯示文字, 再用scanf將底邊的長度記在base變數裡。 "%f"為浮點數的格式指定碼。 &base則是使用&(取址運算子), 得到base這個變數在記憶體的位址, 並告知程式將使用scanf得到的資料儲存給base。 ```c=5 printf("請輸入三角形的高度 : "); scanf("%f", &height); ``` ↑ 同理 ```c=7 printf("三角形的面積為 : %f", base*height/2); ``` 最後用printf將三角形的面積輸出到視窗上, 數值用%f代替,並在逗號後直接計算三角形面積, 即完成題目1.1。 ***(這些程式碼記得用主函式括起來)*** **1.2** ```c= #include <stdio.h> ``` ↑ 一樣include函式庫 ```c=2 float a, b; ``` ↑ 一樣宣告兩個浮點數變數 ```c=3 printf("請輸入a的值 : "); scanf("%f", &a); //使用%f將資料儲存於a位址 printf("請輸入b的值 : "); scanf("%f", &b); //使用%f將資料儲存於b位址 ``` ↑ 與1.1基本相同,只差在變數名稱不一樣 ```c=7 printf("a-b = %f\n", a-b); //輸出題目與答案並換行 printf("b*(a-b) = %f\n", b*(a-b)); //同上 printf("a+b*(a-b) = %f\n", a+b*(a-b)); //同上 printf("[a+b*(a-b)]/b = %f", (a+b*(a-b))/b); // 輸出題目與答案,答案程式碼部分中括號改為小括號 ``` ↑ 「\n」為換行符號,加在""裡面,如"\n"。 一樣是按照題目要求照著輸出, 但最後一行(第10行)的程式碼有中括號, 在計算式中把中括號換成小括號計算, 即完成題目1.2。 ***(這些程式碼也記得用主函式括起來)***