C/ C++,連加求和、乘積(階乘)
FB2:http://gg.gg/TedLeeMicrobitFB/
URL2:http://gg.gg/TedLeeMicrobit/
Line:ted2016.kpvs
Email:Lct4246@gmail.com
FB1:http://gg.gg/TedLeeFB/
Blog:http://gg.gg/TedLeeBlog/
URL1:http://gg.gg/TedLeeURL/
May. 24, 2020
問題解決(Problem Solving)之逻輯思維 =
心法: 程式設計哲思(Philosophical Thinking for Programming) +
技法:程式設計工法(Skills for Programming)
解析:
- 疊代(iteration)法
#include <iostream>
using namespace std;
//sum = 1 + 2 + 3 + ... + j + ... + n
//用i來掃過[1, n],邊掃邊加
int main(void) {
int sum = 0; //保存目前累加和,1 + 2 + 3 + ... + k
int i = 0; //下一個累加值,1 + 2 + 3 + ... + k + i
for (i=1; i<11; i++) {
sum += i;
cout << "i = " << i << endl;
cout << " sum = " << sum << endl;
}
return 0;
}
- 遞迴(recursive)法
#include <iostream>
using namespace std;
int summation(int n) {
if (n == 1) { //base condition
return 1;
}
return (n + summation(n-1)); //recursive formula
}
int main(void) {
int n = 10;
cout << "1+2+3+...+" << n << " = " << summation(n) << endl;
return 0;
}
FB2:http://gg.gg/TedLeeMicrobitFB/
URL2:http://gg.gg/TedLeeMicrobit/
Line:ted2016.kpvs
Email:Lct4246@gmail.com
FB1:http://gg.gg/TedLeeFB/
Blog:http://gg.gg/TedLeeBlog/
URL1:http://gg.gg/TedLeeURL/
URL1:http://gg.gg/TedLeeURL/
May. 24, 2020
問題解決(Problem Solving)之逻輯思維 =
心法: 程式設計哲思(Philosophical Thinking for Programming) +
技法:程式設計工法(Skills for Programming)
解析:
- 疊代(iteration)法
#include <iostream>
using namespace std;//sum = 1 + 2 + 3 + ... + j + ... + n
//用i來掃過[1, n],邊掃邊加
int main(void) {
int sum = 0; //保存目前累加和,1 + 2 + 3 + ... + k
int i = 0; //下一個累加值,1 + 2 + 3 + ... + k + i
for (i=1; i<11; i++) {
sum += i;
cout << "i = " << i << endl;
cout << " sum = " << sum << endl;
}
return 0;
}
- 遞迴(recursive)法
using namespace std;
int summation(int n) {
if (n == 1) { //base condition
return 1;
}
return (n + summation(n-1)); //recursive formula
}
int main(void) {
int n = 10;
cout << "1+2+3+...+" << n << " = " << summation(n) << endl;
return 0;
}
沒有留言:
張貼留言