函数题
6-1 函数重载实现两数相加
int add(int a, int b) {
return a + b;
}
double add(double c, double d) {
return c + d;
}
string add(const string& s1, const string& s2) {
return s1 + s2;
}
6-2 求两个或三个整数中的最大数,用带默认参数的函数实现
int max(int a, int b, int c=0) {
int m=a;
if(b > m) m = b;
if(c > m) m = c;
return m;
}
编程题
7-1 鸿鸿哥分钱
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int x) {
if (x < 2) return false;
for (int i = 2; i <= sqrt(x); i++) {
if (x % i == 0) return false;
}
return true;
}
void findGoldbachPairs(int x, int y) {
for (int i = x; i <= y; i += 2) {
for (int j = 2; j < i; j++) {
int k = i - j;
if (isPrime(j) && isPrime(k)) {
cout << i << "=" << j << "+" << k << endl;
break;
}
}
}
}
int main() {
int x, y;
cin >> x >> y;
findGoldbachPairs(x, y);
return 0;
}
7-2 权值函数Function
#include <iostream>
#include <unordered_map>
using namespace std;
string stringify(int a, int b, int c) {
return to_string(a) + "," + to_string(b) + "," + to_string(c);
}
unordered_map<string, int> memo;
int w(int a, int b, int c) {
string key = stringify(a, b, c);
if (memo.find(key) != memo.end()) {
return memo[key];
}
if (a <= 0 || b <= 0 || c <= 0) {
return memo[key] = 1;
}
if (a > 20 || b > 20 || c > 20) {
return memo[key] = w(20, 20, 20);
}
if (a < b && b < c) {
return memo[key] = w(a, b, c - 1) + w(a, b - 1, c - 1) - w(a, b - 1, c);
} else {
return memo[key] = w(a - 1, b, c) + w(a - 1, b - 1, c) + w(a - 1, b, c - 1) - w(a - 1, b - 1, c - 1);
}
}
int main() {
int a, b, c;
while (true) {
cin >> a >> b >> c;
if (a == -1 && b == -1 && c == -1) break;
cout << "w(" << a << ", " << b << ", " << c << ") = " << w(a, b, c) << endl;
}
return 0;
}
版权所有:浪浪山
文章标题:C plus plus PTA 第二章
文章链接:https://www.langlangshan.cloud/?post=11
本站文章均为原创,未经授权请勿用于任何商业用途
文章标题:C plus plus PTA 第二章
文章链接:https://www.langlangshan.cloud/?post=11
本站文章均为原创,未经授权请勿用于任何商业用途
收藏
扫描二维码,在手机上阅读
推荐阅读: