本课主要介绍了以下内容。
用公式
π 4 = 1 − 1 3 + 1 5 − 1 7 + . . . ( − 1 ) n 1 2 n + 1 , n ∈ 0 , 1 , 2 , . . . \frac{\pi}{4}=1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+...(-1)^n\frac{1}{2n+1}, \quad n \in{0,1,2,...} 4π=1−31+51−71+...(−1)n2n+11,n∈0,1,2,...
求 π \pi π的近似值,直到某一项的绝对值小于 1 0 − 6 10^{-6} 10−6为止。
#include
using namespace std;
//用莱布尼兹级数求圆周率PI
//pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
//直到某一项的绝对值小于1e-6为止
int main() {
double item, pi=0;
int n=1, s=1;
item = 1.0/n;
while(item >= 0.1e-5) {
pi += s*item;
s = -s;
n += 2;
item = 1.0/n;
}
cout << 4*pi << endl;
return 0;
}
#include
using namespace std;
//Greatest Common Divisor(GCD)
int main() {
int m, n, r;
cin >> m >> n;
r = m%n;
while(r!=0) {
m=n;
n=r;
r=m%n;
}
cout << "GCD: " << n << endl;
return 0;
}
小红和小明两人每隔不同的天数都要到福利院去做义工,小红7天去一次,小明15天去一次。有一天,两人恰好在福利院相遇,问至少经过多少天两人又会在福利院相遇?
#include
using namespace std;
/*
小红和小明两人每隔不同的天数都要到福利院去做义工,
小红7天去一次,小明15天去一次。有一天,两人恰好在福利院相遇,
问至少经过多少天两人又会在福利院相遇?
*/
int gcd(int x, int y) {
int r = x%y;
while(r!=0) {
x=y;
y=r;
r=x%y;
}
return y;
}
int main() {
int a, b, i=1;
int m; // LCM
cout<<"Input 2 integer number a and b, Ensure a << endl;
cin>>a>>b;
if(a>b) {
cout << "Please ensure a << endl;
exit(0); //非正常结束程序用abort()
}
m = b*i;
while(m%a!=0) {
i++;
m=b*i;
}
cout << "LCM: " << m << endl;
cout << "GCD: " << gcd(a,b) << endl;
cout << "LCM: " << (a*b)/gcd(a,b) << endl;
return 0;
}
上面的代码中,使用了两种方式来求两个正整数的最小公倍数。
第一种方式使用两个数中较小的那个数是否能整除较大的那个数的倍数,如果能,那么这个倍数即是两个数的最小公倍数。
第二种方式是否能整除是先求两个数的最大公约数,那后利用公式
L C M ( m , n ) = m ∗ n G C D ( m , n ) LCM(m,n) = \frac {m*n} {GCD(m,n)} LCM(m,n)=GCD(m,n)m∗n
来求最小公倍数。
水果店新进了一批桃子,共计1020个。第一天卖了一般多两个,以后每天卖了剩下的一半多两个,问几天以后能卖完这些桃子?
#include
using namespace std;
//水果店新进了一批桃子,共计1020个。第一天卖了一半多两个,
//以后每天卖了剩下的一半多两个,问几天以后能卖完这些桃子?
int main() {
int peaches=1020;
int days=0;
while(peaches!=0) {
peaches = peaches/2 - 2;
days++;
cout << days << ": " << peaches << endl;
}
cout << "Total days: " << days << endl;
return 0;
}
运行程序,输出如下
1: 508
2: 252
3: 124
4: 60
5: 28
6: 12
7: 4
8: 0
Total days: 8
略