数学库常用函数
数学库常用函数
绝对值函数、四舍五入函数、下取整函数、上取整函数、平方根函数、常用三角函数、对数函数、指数函数。
概念
<cmath> 提供与数学相关的库函数:abs/fabs 绝对值;floor/ceil 向下/向上取整;round 四舍五入;sqrt 平方根;还有 sin/cos/tan、log/exp 等。它们接受 double(或整型提升),返回值多为 double,写入 int 变量时常需显式转换。与 cspj.cpp.operator 的区别:库函数是命名调用,不是运算符符号。与 cspj.math.elementary 的区别:后者是数学知识(判别式、几何),这里是 C++ 里怎么写 sqrt/floor。完善程序若出现 floor(sqrt(num)),要选带 #include <cmath> 且类型转换正确的写法。
CSP-J 常考
目前语料只有 1 道:cspj-r1-2024 第 34 题,完善程序空位在 floor/sqrt 组合处,选项区分 (int)floor(sqrt(num)) 与对 num/2 开根等写法。
#include <cmath>
using namespace std;
int num = 17;
int k = (int)floor(sqrt(num)); // sqrt(17)≈4.12,floor 后得 4
cout << k << endl;
易错点
sqrt返回double,直接赋给int会截断小数部分,与floor(sqrt(x))在正数上通常一致,但负数或精度边界要当心。- 忘记
#include <cmath>或写成math.h在竞赛环境一般可用,但阅读题问「能否编译通过」时要看到头文件。 floor/ceil参数与返回值都是浮点,完善程序选项里混用num/2与num要先弄清算法需要的是「平方根下界」还是「一半再开方」。
完善程序共 3 分1 道小题
整组作答后提交批改,成绩计入掌握度 · 已答 0/1
第 1 题
(判断平方数) 问题:给定一个正整数 n,希望判断这个数是否为完全平方数,即存在一个正整数 x,使得 x 的平方为 n。
试补全程序。
#include<iostream>
#include<vector>
using namespace std;
bool isSquare(int num) {
int i = ___①___;
int bound = ___②___;
for (; i <= bound; ++i) {
if (___③___) {
return ___④___;
}
}
return___⑤___;
}
int main() {
int n;
cin >> n;
if (isSquare(n)) {
cout << n << " is a square number" << endl;
} else {
cout << n << " is not a square number" << endl;
}
return 0;
}
程序
1
#include<iostream>2#include<vector>3using namespace std;45bool isSquare(int num) {6 int i = ___①___;7 int bound = ___②___;8 for (; i <= bound; ++i) {9 if (___③___) {10 return ___④___;11 }12 }13 return___⑤___;14}1516int main() {17 int n;18 cin >> n;19 if (isSquare(n)) {20 cout << n << " is a square number" << endl;21 } else {22 cout << n << " is not a square number" << endl;23 }24 return 0;25}- 34(②)单选空位 ②3 分
② 处应填( )