习题2-1 水仙花数
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a = 0, b = 0, c = 0;
for (int i = 100; i < 1000; ++i)
{
a = floor(i / 100);
b = floor((i - 100 * a) / 10);
c = i - 100 * a - 10 * b;
if (i == pow(a, 3) + pow(b, 3) + pow(c, 3))
cout << i << endl;
}
return 0;
}
习题2-2 韩信点兵
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a = 0, b = 0, c = 0;
vector<vector<int>> v;
while (cin >> a >> b >> c)
{
vector<int> v1;
v1.push_back(a);
v1.push_back(b);
v1.push_back(c);
v.push_back(std::move(v1));
}
int record = 1;
for (auto c : v)
{
int result = 0;
result = c[0] * 70 + c[1] * 21 + c[2] * 15;//这里面用到了中国剩余定理,一步就能算出来结果,有兴趣的童鞋可以找找相关资料
while (result > 100)
result -= 105;
if (result < 10)
cout << "Case" << record << ": " << "No answer\n";
else
cout << "Case" << record << ": " << result << endl;
++record;
}
return 0;
}
习题2-3 倒三角形
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter the height of the triangle:\n";
int n = 0;
cin >> n;
int space = 0;
for (; n > 0; --n)
{
int j = space++;
while (j-- > 0)
cout << " ";
int c = 2 * n - 1;
while (c-- > 0)
cout << "#";
cout << endl;
}
return 0;
}
习题2-4 子序列的和
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>//控制输出小数的位数
using namespace std;
int main()//题目所说的陷阱可能是指当输入过大的时候会出现溢出的情况,对于int是16位的会发生这个问题,如果是32位就不必在意了
{
int n = 1, m = 1;//如果int是16位的,需要声明为long int
vector<pair<int, int>> v;
while (cin >> n >> m)
{
if (n == 0 && m == 0)
break;
auto p = make_pair(n, m);
v.push_back(p);
}
for (size_t i = 0; i < v.size(); ++i)
{
int n1 = v[i].first;
int m1 = v[i].second;
double result = 0.0;
for (double j = n1; j <= m1; ++j)
{
result += 1 .0/ j / j;
}
cout << "Case " << i+1 << ": " << fixed << setprecision(5) << result << endl;
}
return 0;
}
习题2-5 分数化小数
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>//控制输出小数的位数
using namespace std;
int main()
{
int n = 0, m = 0,p = 0;
vector<vector<int>> v;
while (cin >> n >> m >> p)
{
if (n == 0 && m == 0 && p == 0)
break;
v.push_back({ n, m, p });
}
for (size_t i = 0; i < v.size(); ++i)
{
double result = (double)v[i][0]/(double)v[i][1];
cout << "Case " << i + 1 << ": " << fixed << setprecision(v[i][2])<<result << endl;
}
return 0;
}
习题2-6 排列
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>//控制输出小数的位数
using namespace std;
void FindUsedNum(vector<bool> &v,int i)//函数功能是用来找到i的个十百位,并设置v[x]为1
{
v[i / 100] = 1;
v[(i % 100) / 10] = 1;
v[i % 10] = 1;
}
int main()
{
vector<bool> v;
for (int i = 123; i <= 329; ++i)//注意到只有当i>=123,且i<=329才符合题意
{
v.assign(10, 0);//注意这个容器的大小是10而不是9,方便操作
FindUsedNum(v, i);
FindUsedNum(v, 2*i);
FindUsedNum(v, 3 * i);
int record = 0;
for (const auto &c : v)
record += c;
if (record == 9)
cout << i << "\t" << 2 * i << "\t" << 3 * i << "\t" << endl;
}
return 0;
}
#include <vector>
#include <cmath>
#include <iomanip>//控制输出小数的位数