This article explains how to find powers, absolute values, square roots, and remainders using the C++ math.h library. These calculations are used frequently in competitive programming, so please take a look.
math.h
math.h is a library that enables calculations such as those described in the title. In addition to these, calculations of trigonometric functions such as sin and cos are also possible with this library. To use, first load the header file as follows.
#include<math.h>
Functions
The following table shows the functions corresponding to each calculation. The table shows that for all functions, the return type is double.
Calculation Method | function | Description | Return type of the function |
power | pow(x, y) | x squared y | double |
absolute | fabs(x) | Absolute value of x | double |
square root | sqrt(x) | Square root of x | double |
cubic root | cbrt(x) | Cubic root of x | double |
remainder | fmod(x, y) | Remainder of y divided by x | double |
Output example
Sample Code
Here is a sample code that uses the above functions.
タイトル:math.cpp
#include <iostream> #include<math.h> using namespace std; int main(){ cout << "power" << endl; cout << pow(2,2) << endl; //The power cout << pow(4,0.5) << endl;//The power cout << "absolute value" << endl; cout << fabs(-10543) << endl;//absolute value cout << fabs(-10) << endl;//absolute value cout << "square root" << endl; cout << sqrt(9) << endl; //square root cout << sqrt(20) << endl; //square root cout << "cube root" << endl; //square root cout << cbrt(8) << endl; //cube root cout << cbrt(16) << endl; //cube root cout << "remainder(remainder)" << endl; cout << fmod(6,2) << endl; // remainder(remainder) cout << fmod(-10,3) << endl; // remainder(remainder) return 0; }
Output result
タイトル:出力結果
power 4 2 Absolute value 10543 10 Square root 3 4.47214 Cubic root 2 2.51984 Surplus (surplus) 0 -1
Summary
This article explained how to calculate powers, absolute values, square roots, and remainders in C++. The following is a summary of the contents.
- The above calculations can be performed by using math.h
- When performing arithmetic operations, the return value is of type double.
In addition to these calculations, there are other calculations that can be performed with math.h, which will also be introduced in the future.