数学函数

用 <cmath> 里的 sqrt、pow、abs、ceil、floor 开方、乘方、取整。

讲第 1 步,共 7 步

没有符号的运算

开平方、乘方这些运算没有现成的符号,要用 <cmath> 这套工具里的「函数」:写函数名,括号里放要算的数,就得到结果。

#include <iostream>
#include <cmath>
using namespace std;
​
int main() {
cout << sqrt(16) << " " << pow(2, 10) << endl;
cout << abs(-5) << endl;
cout << ceil(2.1) << " " << floor(2.9) << endl;
return 0;
}
输出
4 1024
5
3 2
  • sqrt(x):x 的平方根。sqrt(16) 是 4。
  • pow(a, b):a 的 b 次方。pow(2, 10) 是 1024。
  • abs(x):绝对值,去掉负号。
  • ceil(x) 向上取整(2.1 变 3),floor(x) 向下取整(2.9 变 2),round(x) 四舍五入。

sqrt、pow、ceil、floor 算出来的都是 double。数一大,cout 就显示成科学计数法:

#include <iostream>
#include <cmath>
using namespace std;
​
int main() {
cout << pow(2, 30) << endl;
cout << (long long)pow(2, 30) << endl;
return 0;
}
输出
1.07374e+09
1073741824

1.07374e+09 的意思是 1.07374 × 10^9,只留了 6 位数字。要整数就像第二行那样,换成 long long 再输出。

平方直接写 x * x,比 pow(x, 2) 简单,结果也一定是整数。