C++ 上机课参考答案
本系列文章供北京邮电大学信通院及数媒学院「C++高级程序语言设计」上机课学生参考。
2016-2017学年第二学期C++第五章(2)
1511.VC++实验5.3 斐波那契数列
#include <iostream>
using namespace std;
int fibonacci(
int n)
{
int a =
1, b =
1, temp;
if(n ==
1 || n ==
2)
return 1;
for(
int i =
3; i <= n; i++)
{
temp = a + b;
a = b;
b = temp;
}
return b;
}
int main()
{
int n;
cin >> n;
cout << fibonacci(n) << endl;
return 0;
}
1512.VC++实验5.4 计算排列
#include <iostream>
using namespace std;
int factorial(
int x)
{
int factorial =
1;
for(
int i =
1; i <= x; i++)
{
factorial *= i;
}
return factorial;
}
int fun(
int n,
int m)
{
return factorial(n) / factorial(n - m);
}
int main()
{
int n, m;
cin >> n >> m;
cout << fun(n, m) << endl;
return 0;
}
1514.VC++实验5.6 分糖果
#include <iostream>
using namespace std;
static int a[
10];
int pass()
{
int temp = a[
9];
for(
int i =
9; i >
0; i--)
{
a[i] = a[i] /
2 + a[i -
1] /
2;
}
a[
0] = a[
0] /
2 + temp /
2;
for(
int i =
0; i <
10; i++)
if(a[i] %
2 !=
0)
a[i]++;
}
int judge()
{
int sum =
0, n =
0;
while(
1)
{
for(
int i =
0; i <
10; i++)
sum += a[
0] - a[i];
if(sum ==
0)
{
cout << n <<
" " << a[
0] << endl;
return 0;
}
pass();
n++;
sum =
0;
}
}
int main()
{
for(
int i =
0; i <
10; i++)
cin >> a[i];
judge();
return 0;
}