1.输出斐波纳契数列:1,1,2,3,5,8…的前20个数
#include <iostream>
int main()
{
int a[20];
a[0] = 1;
a[1] = 1;
for (int i = 2; i < 20; i++)
{
a[i] = a[i - 1] + a[i - 2];
}
for (i = 0; i < 20; i++)
{
std::cout << a[i] << "\t";
}
return 0;
}
2.输入5个数到数组中,输出所有大于5个数平均值的数。
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a(5);
int sum = 0;
std::cout << "Please enter 5 integers:" << std::endl;
for (int i = 0; i < 5; i++)
{
std::cin >> a[i];
}
std::cout << std::endl;
for (i = 0; i < 5; i++)
{
sum += a[i];
}
for (i = 0; i < 5; i++)
{
if ((a[i] * 5) > sum)
{
std::cout << a[i] << "\t";
}
}
std::cout << "is above the mean." << std::endl;
return 0;
}
3.编写函数,求级数S=1+2+3+...n,并在主函数中求:
#include <iostream>
float series(int n);
int main()
{
float s;
s = (series(3) + series(4) + series(5)) / (series(6) + series(7));
std::cout << "y = " << s << std::endl;
return 0;
}
float series(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
return sum;
}
4.编写一函数求n!,并用函数调用实现1!+2!+3!+……+n!
示例:输入 4
输出 33(注:1!+2!+3!+4!=33)
#include <iostream>
int func(int n);
int main()
{
int a, sum = 0;
std::cout << "Please enter an integer:" << std::endl;
std::cin >> a;
for (int i = 1; i <= a; i++)
{
sum += func(i);
}
std::cout << sum << std::endl;
return 0;
}
int func(int n)
{
int s = 1;
for (int i = 1; i <= n; i++)
{
s *= i;
}
return s;
}
5.验证哥德巴赫猜想:100以内的任意偶数均可分解为两个素数的和。
示例:输出:
#include <iostream>
int judge(int n);
int main()
{
for (int i = 4; i <= 100; i += 2)
{
for (int j = 2, m = 0; j < i; j++)
{
if (judge(j) && judge(i - j))
{
m = i - j;
std::cout << i << " = " << j << " + " << m << std::endl;
break;
}
}
}
return 0;
}
int judge(int n)
{
if (n == 1) return 0;
for (int i = 2; i < n; i++)
{
if (n % i == 0) return 0;
}
return 1;
}