--- tags: 承威, 作業, C --- # 本利和題目 ![S__4349956](https://hackmd.io/_uploads/ryjl5v2VT.png) ## 完整程式 :::spoiler 點我展開 ```c= #include <stdio.h> float interest(int principal, double rate, int years){ float total = 0; for (int i = 0; i < years; i++){ total += (float)principal * rate; } return total; } int main() { int user_principal = 0; float user_rate = 0; int user_years = 0; printf("本金 => "); scanf("%d", &user_principal); printf("利率 => "); scanf("%f", &user_rate); printf("年限為 => "); scanf("%d", &user_years); printf("%d年 本利和%.6f\n", user_years, user_principal + interest(user_principal, user_rate, user_years)); return 0; } ``` ::: ## 分解步驟 1. 定義 interest 函數 ```c= float interest(int principal, double rate, int years){ float total = 0; for (int i = 0; i < years; i++){ total += (float)principal * rate; } return total; } ``` >第1行定義函數interest,題目圖片裡面本利和是有小數點的,所以函數本身的資料型態要用double或是float這兩種浮點數 >接著給這個函數三個參數principal 本金、rate 利率、years 年限,這裡利率是以小數輸入,所以也要是浮點數 > >第3行我定義了一個變數`total`來儲存總利息 > >第4行`(float)principal`中的`(float)`是把int型態的{principal|本金}轉換成float才可以跟其他浮點數一同計算 > >最後return總利息 :::warning 也可以return總利息+本金,最後print出答案時就不用再加本金了 ::: 2. 主程式 main 可以分三部分 >1. 定義需要的資料 ```c=12 int user_principal = 0; float user_rate = 0; int user_years = 0; ``` >2. 輸入 ```c=18 printf("本金 => "); scanf("%d", &user_principal); printf("利率 => "); scanf("%f", &user_rate); printf("年限為 => "); scanf("%d", &user_years); ``` >3. 計算&輸出 ```c=25 printf("%d年 本利和%.6f\n", user_years, user_principal + interest(user_principal, user_rate, user_years)); ``` >只有這個是比較難理解的地方 > >首先{print format|輸出格式}`"%d年 本利和%.6f\n"`有兩個{format specifier|格式指定字} >`%d`與`%.6f`也就是整數與浮點數,其中`%.6f`的.6是只顯示到小數後第幾位 >那麼有兩個格式指定字,就會有兩個要放入的資料`user_years`與`user_principal + interest(user_principal, user_rate, user_years)` >第一個就只是顯示年份,所以我們解釋後面那一長串就好 > >{user_principal|使用者輸入的本金}   +   {interest(user_principal, user_rate, user_years)|我們建立用於計算利息的函數,會return總利息} >