Skip to content

Instantly share code, notes, and snippets.

@40823149
Created December 31, 2019 14:49
Show Gist options
  • Save 40823149/db6852a808db02b5a69127765af05600 to your computer and use it in GitHub Desktop.
Save 40823149/db6852a808db02b5a69127765af05600 to your computer and use it in GitHub Desktop.
加總
// 在所有函式定義外圍所宣告的變數, 稱為全域變數, 有效範圍包含各函式內部與外部
// for 迴圈所使用的索引值, 宣告為整數 (integer)
int i;
// 累加起始值 start 宣告為整數, 且設為 1
int start = 1;
// 累加終止值 end 宣告為整數, 且設為 10
int end = 10;
// 累加總數值 sum 宣告為整數
int sum;
// 定義 main() 主函式內容, 目的在利用 for 迴圈進行整數的累加
main(){
// 將前面已經宣告為全域整數的變數 sum 設為 0, 表示從 0 開始進行累加
sum = 0;
// 執行 for 迴圈內的整數累加設計, 使用前面已經宣告為全域整數的 i 作為索引變數
// 分別從 start 開始累加至 end, 且每次迴圈的索引值增加 1
for(i=start;i <= end ;i++){
// 當索引變數 i 所對應的值小於或等於 end 時, 對 sum 變數加上 i
sum += i;
// 可以在 for 迴圈每一個階段運算時, 列出當時的 sum 對應值, 查驗是否正確
//print("$sum");
}
// for 迴圈累加完成後, 列出最後訊息
print('從 $start 累加至 $end 的總數值為 $sum');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment