GESP2024年12月认证C++二级( 第三部分编程题(1)寻找数字)
参考程序(枚举):
#include <iostream>
//#include <cmath>
using namespace std;int main() {int t;cin >> t;while (t--) {long long a;cin >> a;bool found = false;// 枚举 b for (long long b = 1; b * b * b * b <= a; b++) {if (b * b * b * b == a) {cout << b << endl;found = true;break;}}if (!found) {cout << -1 << endl;}}return 0;
}
参考程序(数学函数sqrt):
#include <iostream> // 用于输入输出
#include <cmath> // 用于 sqrt 函数
using namespace std;int main() {int t; // 读入测试数据组数cin >> t;while (t--) { // 对每组测试数据进行处理int a;cin >> a; // 输入正整数 a// sqrt(sqrt(a)) 表示开四次方// 将结果强转为整数,向下取整int b = (int)(sqrt(sqrt(a)));// 判断这个 b 是否满足 b^4 == a// 这里不能直接用浮点比较,所以用整数乘法if (b * b * b * b == a) {cout << b << endl; // 如果是 b 的四次方,输出 b} else {cout << -1 << endl; // 否则输出 -1}}return 0;
}