導入
平方根・べき乗・切り上げなどの数学計算は、<cmath> の関数で行えます。
説明
<cmath> を include すると、sqrt(平方根)・pow(べき乗)・abs(絶対値)などが使えます。
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(16.0) << endl; // 4(平方根)
cout << pow(2, 10) << endl; // 1024(2の10乗)
cout << abs(-7) << endl; // 7(絶対値)
return 0;
}
切り上げ ceil・切り捨て floor もあります。
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << ceil(3.2) << endl; // 4(切り上げ)
cout << floor(3.8) << endl; // 3(切り捨て)
return 0;
}
表示する小数の桁数をそろえたいときは、<iomanip> の fixed と setprecision を使います。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265;
cout << fixed << setprecision(2) << pi << endl; // 3.14
return 0;
}
やってみよう
sqrt や pow にいろいろな数を渡して、結果を確かめましょう。setprecision の桁数を変えて表示の違いも見てください。
演習
<cmath> を使って、3 の 4 乗(pow(3, 4))を表示してください(結果は 81)。
ヒント1を見る
#include <cmath> を書き、cout << pow(3, 4) << endl;。