C++ numbers
Usually, when we need to use numbers, we use primitive data types, such as int, short, long, float, double, etc. These data types for numbers, their possible values and numerical ranges, were discussed in the chapter C++ Data Types.
C++ Defining Numbers
We have defined numbers in various instances in previous chapters. Here is a comprehensive example of defining various types of numbers in C++:
#include <iostream> using namespace std; int main () { // 数字定义 short s; int i; long l; float f; double d; // 数字赋值 s = 10; i = 1000; l = 1000000; f = 230.47; d = 30949.374; // 数字输出 cout << "short s :" << s << endl; cout << "int i :" << i << endl; cout << "long l :" << l << endl; cout << "float f :" << f << endl; cout << "double d :" << d << endl; return 0; }
When the above code is compiled and executed, it produces the following results:
short s :10 int i :1000 long l :1000000 float f :230.47 double d :30949.4
C++ Mathematical Operations
In C++, in addition to creating various functions, it also contains various useful functions for you to use. These functions are written in the standard C and C++ libraries and are called built-in functions. You can reference these functions in your program.
C++ has a rich set of built-in mathematical functions that can perform operations on various numbers. The following table lists some useful built-in mathematical functions in C++.
To take advantage of these functions, you need to reference the math header file <cmath>.
Serial number | Function & Description |
---|---|
double cos( double);This function returns the cosine of the radian angle (double type). | |
double sin(double);This function returns the sine of the angle in radians (double type). | |
double tan(double);This function returns the tangent of the radian angle (double type). | |
double log(double);This function returns the natural logarithm of the parameter. | |
double pow(double, double);Assume the first parameter is x and the second parameter is y , then the function returns x raised to the yth power. | |
double hypot(double, double);This function returns the square root of the sum of the squares of the two parameters, that is Say, the parameters are two right-angled sides of a right triangle, and the function will return the length of the hypotenuse. | |
double sqrt(double);This function returns the square root of the parameter. | |
int abs(int);This function returns the absolute value of an integer. | |
double fabs(double);This function returns the absolute value of any decimal number. | |
double floor(double);This function returns the largest integer that is less than or equal to the passed parameter. |