目录
乘方运算
#include <iostream>
using namespace std;
int main()
{
int resutlt, a, n;
cin >> a >> n;
int result = 1;
for (int i = 0; i < n; i++)
result *= a;
cout << result;
return 0;
}
cin输入的好处
若干整数的最大值
#include <iostream>
using namespace std;
int main()
{
int n, max;
cin >> max; //先向max赋予第一个输入值
while (cin >> n)
{
if(n > max) max = n;
}
cout << max << endl;
return 0;
}
输入完输入Ctrl + Z / Ctrl + D(结束标志符)
附注 scanf()的值 scanf(“%lf”)
若 3.4 ,值1
若 n, 值0
若EOF, 值-1
斐波那契数列
#include <iostream>
using namespace std;
int main()
{
int pre ,lat;
pre = lat = 1;
int m;
int k;
cin >> k;
for(int i = 0; i < k - 2; i++)
{
m = pre + lat;
pre = lat;
lat = m;
}
cout << lat;
return 0;
}
求1!+2!+3!+……+n!
繁琐版
#include <iostream>
using namespace std;
int main()
{
int n;
int sum = 0, fact;
int i, k;
cin >> n;
for(i = 1; i <= n; i++)
{
for(fact = 1, k = 1; k <= i; k++)
{
fact *= k;
}
sum += fact;
}
cout << sum;
return 0;
}
紧凑版
#include <iostream>
using namespace std;
int main()
{
int n;
int sum = 0, fact;
int i, k;
cin >> n;
for(i = 1; i <= n; i++)
{
fact *= i; //注意2!与3!的关系
sum += fact;
}
cout << sum;
return 0;
}
求不大于n的全部质数(100为例)
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n;
int i, k;
int flag = 1;
cin >> n;
int m =2;
printf("%2d ", m);
for(i = 3; i <=n; i += 2) //筛除偶数
{
for(k = 3; k < i; k += 2) //判断i是否为质数
{
if(i % k == 0) break;
if(k * k > i) break;
}
if(k * k > i)
{
flag++;
printf("%2d ", i);
if(flag % 5 == 0)
{
printf("\n");
flag = 0;
}
}
}
return 0;
}
输出结果
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
感想:高手的答案总经过进一步改进,更加简洁