Numbers in C++:
Normally, when we work with numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.
Defining Numbers in C++:
We already defined numbers in various example given in previous chapters. Here is another consolidated example to define various types of numbers of C++.
/*Defining Numbers: InfoBrother:*/
#include<iostream>
using namespace std;
main()
{
//Numbers defining:
short s;
int i;
long l;
float f;
double d;
//assigning numbers;
s=10;
i=100;
l=100000;
f=25.5;
d=2455.52;
//display result:
cout<<" short :" <<s<<endl;
cout<<" int :" <<i<<endl;
cout<<" long :" <<l<<endl;
cout<<" float :" <<f<<endl;
cout<<" double :"<<d<<endl;
return 0;
}
Numbers
short :10 int :100 long :100000 float :25.5 double :2455.52
Math Operation in C++:
In addition to the various functions we can create, C++ also includes some useful functions we can use. these functions are available in Standard C and C++ libraries and called built-in functions. These are functions that can be include in our program and then use.
C++ has rich set of mathematical operations, which can be performed on various numbers. following table lists down some useful built-in mathematical functions available in C++.
Functions | Syntax | Purpose |
Trigonometric Functions | ||
---|---|---|
cos | double cos(double x); | This function is used to return the cosine of an angle of X radians. It required an Parameter "x" representing an angle expressed in radians. (One radian is equal to 180/PI degrees.) |
sin | double sin(double x); | This function is used to return the sine of an angle of X radians. Its required an parameter "x" representing an angle expressed in radians. (One radian is equal to 180/PI degrees.) |
tan | double tan(double x); | This function is used to return the tangent of an angle of X radians. Its required an pareamter "x" representing an angle expressed in radians. (one radian is equal to 180/PI degrees.) |
acos | double acos(double x); | This function is used to return the principal value of the arc cosine In Trigonometrics, arc cosine is the inverse operation of cosine. of x, expressed in radians. It required an parameter "x" whose arc cosine is computed, in the interval [-1, +1]. if the argument is out of this interval, a domain error occurs. |
asin | double asin(double x); | This function is used to returns the principal value of the arc sine In Trigonometrics, arc sine is the inverse operation of sine. of x, expressed in radians. It required an parameter "x" whose arc sine is computed, in the interval [-1, +1]. if the argument is out of this interval, a domain error occurs. |
atan | double atan(double x); | This function is used to return the principal value of the arc tangent In Trigonometrics, arc tangent is the inverse operation of tangent. of x, expressed in radians. It required an Parameter "x" whose arc tangent is computed. |
atan2 | double atan2(double y, double x); | This function is used to return the principal value of the arc tangent In Trigonometric, arc tangent is the inverse operation of tangent. of y/x, expressed in radians. to compute the value, the function takes into account the sign of both arguments in order to determine the quadrant. this function required two arguments "Y" representing the proportion of the y-coordinate. and "x" representing the proportion of the x-coordinate. if both arguments passed are zero, a domain error occurs. |
Hyperbolic Functions | ||
cosh | double cosh(double x); | This function is used to return the hyperbolic cosine of x. this function required one paremeter "x" representing a hyperbolic angle. |
sinh | double sinh(double x); | This function is used to return the hyperbolic sine of x. This function required one parameter "x" representing a hyperbolic angle. |
tanh | double tanh(double x); | This function is used to return the hyperbolic tangent of x. this function required one paremeter "x", representing a hyperbolic angle. |
acosh | double acosh(double x); | This function is used to return the non negative area hyperbolic cosine The area Hyperbolic cosine is the inverse operation of the hyperbolic cosine. This function required a parameter "x", whose area hyperbolic cosine is computed. if the argument is less than 1, a domain error occurs. |
asinh | double asinh(double x); | This function is used to return the area hyperbolic sine The area hyperbolic sine is the inverse operation of the hyperbolic sine. of x. this function required an parameter whose area hyperbolic sine is computed. |
atanh | double atanh(double x); | This function used to return the area hyperbolic tangent The area hyperbolic tangent is the inverse operation of the Hyperbolic tangent. of x. This function required an parameter whose area hyperbolic tangent is computed, in the interval [-1 , +1] if the argument is out of this interval, a domain error occurs. for value of -1 and +1, a pole error may occur. |
Exponential and Logarithmic Functions | ||
exp | double exp(double x); | This function is used to returns the base-e exponential function of x, which is e raised to the power x:ex. |
frexp | double frexp(double x, int* exp); | This function is used to breaks the floating point number x into its binary significanda floating point with an absolute value between 0.5(include) and 1.0(excluded) and an integral exponent for 2. This function required two parameter, "x" value to be decomposed and "exp" pointer to an int where the value of the exponent is stored. |
ldexp | double ldexp(double x, int exp); | This function is used to return the result of multiplying x(the significant) by 2 raised to the power of exp (the exponent). this function required two parameters. "x" floating point value representing the significant and "exp" value of the exponent. |
log | double log(double x); | This function used to return the Natural Logarithm The Neutral logarithm is the base-e logarithm. the inverse of the natural exponential function (exp). for common (base-10) logarithms, see log10 . of x. this function required one parameter "x" whose logarithm is calculated. if the argument is negative, a domain error occurs. |
log10 | double log10(double x); | This function used to return the common (base-10) logarithm of x. this function required an parameter "x" whose logarithm is calculated. if the argument is negative, a domain error occurs. |
modf | double modf(double x, double* intpart); | Breaks x into an integral and a fractional part. The integer part is stored in the object pointed by intpart, and the fractional part is returned by the function. both parts have the same sign as x. this function required two arguments. "x" floating point value to break into parts. and "intpart" pointer to an object (of the same type as x) Where the integral part is stored with the same sign as x. |
exp2 | double exp2(double x); | This function is used to return the base-2 exponential function of x, which is 2 reised to the power x: 2x. this function need an argument "x" value of the exponent. |
expm1 | double expm1(double x); | This function is used to return e raised to the power x minus one: ex-1. This function required an argument "x", value of the exponent. |
ilogb | int ilogb(double x); | This function is used to return the integral part of the logarithm of |x|, using FLT_RADIX Base for all floating-point types (float, double, and logn double). as base for the logarithm. This function need an argument "x", value whose ilogb is returned. |
log1p | double log1p(double x); | This function is used to return the natural logarithm of one plus x. This function need an argument "x" whose logarithm is calculated. if the argument is less than -1, a domain error occurs. |
log2 | double log2(double x); | This function is used to return the binary (base-2) logarithm of x. this function required an parameter "x" whose logarithm is calculated. if the argument is negative, a domain error occurs. |
logb | double logb(double x); | This function is used to return the logarithm of |x|, using FLT_RADIX Base for all floating-point types (float, double, and logn double). as base for the logarithm. this function need an argument "x" value whose logarithm is calculated. |
scalbn | double scalbn(double x, int n); | Scales x by FLT_RADIX Base for all floating-point types (float, double, and logn double). to the power of n, returning the same as: scalbn(x,n) = x * FLT_RADIXn Presumably, x and n are the components of a floating-point number in the system; in such a case, this function may be optimized to be more efficient than the theoretical operations to compute the value explicitly. This function required two arguments, "x" value representing the significant, and "exp" value of the exponent. |
scalbln | double scalbln(double x, long int n); | Scales x by FLT_RADIX Base for all floating-point types (float, double, and logn double). raised to the power of n, returning the result of computing: scalbn(x,n) = x * FLT_RADIXn Presumably, x and n are the components of a floating-point number in the system; in such a case, this function may be optimized to be more efficient than the theoretical operations to compute the value explicitly. This function required two arguments, "x" value representing the significant, and "exp" value of the exponent. |
Power Functions | ||
pow | double pow(double base, double exponent); | This function is used to return the base raised to the power exponent. This function required two arguments, "base" base value, and "exponent" Exponent value. |
sqrt | double sqrt(double x); | This function is used to return the square root of x. This function need an argument "x" whose square root is computed. if the argument is negative, a domain error occurs. |
cbrt | double cbrt (double x); | This function is used to return the cubic root of x. Need an argument whose cubit root is computed. |
hypot | double hypot(double x, double y); | This function is used to return the hypotenuse The longest side of a right-angled triangle, opposite the right angle. of a right-angled triangleA right angle triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). whose legs are x and y. |
Error and Gamma Functions | ||
erf | double erf(double x); | This function is used to return the error function value for x. This function need an parameter "x" for the error function. |
erfc | double erfc(double x); | This function is used to return the complementary error function The complementary error function is equivalent to: erfc(x) = 1-erf(x); for x. This function required an parameter "x" for the complementary error function. |
tgamma | double tgamma(double x); | This function is used to return the gamma function of x. this function required an parameter "x" for the gamma function. |
lgamma | double lgamma(double x); | This function is used to return the natural logarithm of the absolute value of the gamma function of x. This function required an argument "x" for the log-gamma function. |
Rounding and remainder Functions | ||
ceil | double ceil(double x); | Rounds x upward, returning the smallest integral value that is not less than x. This function required an argument "x" to round up. |
floor | double floor(double x); | Rounds x downward, returning the largest integral value that is not greater than x. This function need an argument to round down. |
fmod | double fmod(double numer, double denom); | This function is used to return the floating-point remainder of numer/denom (rounded towards zero). This function required two arguments, "numer" value of the quotient numerator, and "denom" value of the quotient denominator. |
trunc | double trunc(double x); | Round x toward zero, This function used to return the nearest integral value that is not larger in magnitude than x. This function need an argument "x" to truncate. |
round | double round(double x); | This function is used to returns the integral value that is nearest to x, with halfway cases rounded away from zero. |
lround | long int lround(double x); | This function is used to return the value that is nearest in value to x, with halfway cases rounded away from zero. |
llround | long long int llround(double x); | This function is used to returns the integer value that is nearest in value to x, with halfway cases rounded away from zero. The rounded value is returned as a value of type long long int. |
rint | double rint(double x); | Rounds x to an integral value, using the rounding direction specified by fegetround Returns a value that indicates the rounding direction mode, as specified in the current floating point environment. This function required an argument "x" to round. |
lrint | long int lrint(double x); | Rounds x to an integral value, using the rounding direction specified by getgetround, and returns it as a value of type long int. |
llrint | long long int llrint(double x); | Rounds x to an integral value, using the rounding direction specified by fegetround, and return it as a value of type long long int. |
nearbyint | double nearbyint(double x); | Rounds x to an integral value, using the rounding direction specified by fegetround. |
remainder | double remainder(double numer, double denom); | This function is used to return the floating-point remainder of numer/denom (rounded to nearest). This function need two argument, "numer" value of the Quotient numerator, and "denom" value of the Quotient denominator. |
remquo | double remquo(double numer, double denom, int* quot); | This function is used to returns the same as remainder, but it additionally stores the Quotient internally used to determine its result in the object pointed by quot. this function need three arguments, "numer" floating point value with the quotient numerator. "denom" Floating point value with the quotient denominator and "quot" Pointer to an object where the quotient internally used to determine the remainder is stored as a value of type int. |
Floating-point Manipulation Functions | ||
copysign | double copysign(double x, double y); | This function is used to return a value with the magnitude of x and the sign of y. This function need two arguments, "x" value with magnitude of the resulting value. and "y" value with the sign of the resulting value. |
nan | double nan(const char* tagp); | This Function is used to return a quiet NaN (Not-A-Number) The NaN values are used to identify undefined or non-re presentable values for floating-point elements, such as the square root of negative numbers or the result of 0/0. This function required an argument "tagp" An implementation-specific C-string. if this is an empty string (""), the function returns a generic NaN value ( the same as returned by passing "NaN" to strtod This function used to convert string to double) |
nextafter | double nextafter(double x, double y); | This function is used to return the next re presentable value after x in the direction of y. This function need two arguments, "x" Base value, "y" value toward which the return value is approximated. if both parameters compare equal, the function returns y. |
nexttoward | double nexttoward(double x, long double y); | This function is used to returns the next re presentable value after x in the direction of y. This function required two arguments, "x" base value, and "y" value toward which the return value is approximated. if both parameters compare equal, the function returns y ( converted to the return type ). |
Minimum, Maximum, difference Functions | ||
fdim | double fdim(double x, double y); | This function is used to returns the positive difference between x and y. this function required two arguments "x" and "y", whose difference between x and y. |
fmax | double fmax(double x, double y); | This function is used to return the larger of its arguments either x or y. if one of the arguments in a NaN (Not-A-Number) The NaN values are used to identify undefined or non-re presentable values for floating-point elements, such as the square root of negative numbers or the result of 0/0., the other is returned. |
fmin | double fmin(double x, double y); | This function is used to returns the smaller of its arguments either x or y. if one of the arguments in a NaN (Not-A-Number) The NaN values are used to identify undefined or non-re-presentable values for floating-point elements, such as the square root of negative numbers or the result of 0/0., the other is returned. |
Some Other Useful Functions | ||
fabs | double fabs(double x); | This function is used to returns the absolute value The magnitude of a real number without regard to its sign. of x: |x|. |
abs | int abs (int n); | This function is used to return the absolute value of parameter n. |
fma | double fma(double x, double y, double z); | This function computes the result without losing precision in any intermediate result. (Returns: x*y+z;) This function required two arguments , "x, y" values to be multiplied. and "z" value to be added. |
/*<math.h> Operation: InfoBrother:*/
#include<iostream>
#include<math.h> //required for math operations:
using namespace std;
main()
{
//Number Definition:
short s=10;
int i=-100;
long l=10000;
float f=230.52;
double d=200.332;
//Mathematical Operations:
cout<<"sin(d): "<<sin(d) <<endl;
cout<<"cos(d): "<<cos(d) <<endl;
cout<<"acos(d): "<<acos(d) <<endl;
cout<<"abs(i): "<<abs(i) <<endl;
cout<<"floor(d): "<<floor(d) <<endl;
cout<<"sqrt(f): "<<sqrt(f) <<endl;
cout<<"pow(d,2): "<<pow(d,2) <<endl;
cout<<"cosh(d): "<<cosh(d) <<endl;
cout<<"exp(d): "<<exp(d) <<endl;
cout<<"log(d): "<<log(d) <<endl;
cout<<"trunc(d): "<<trunc(d) <<endl;
cout<<"rint(d): "<<rint(d) <<endl;
return 0;
}
< Math.h >
sin(d) :-0.666817 cos(d) :0.745221 acos(d) :nan abs(i) :100 floor(d):200 sqrt(f) :15.1829 pow(d,2):40132.9 cosh(d) :5.03561e+086 exp(d) :1.00712e+087 log(d) :5.29998 trunc(d):200 rint(d) :200
Random Numbers In C++:
There are many cases where we wish to generate a random number. There are actually two function we will need to knwo about random number generation. The first is rand(), This function will only return a pseudo random number in the range from 0.0 to 32,767. The maximum value is Library-dependent, but is guaranteed to be at least 32767 on any standard library implementation. we can check it from RAND_MAX.
#include <iostream>
#include <cstdlib> //required for rand() function:
using namespace std;
main()
{
int i = 0;
while(i++ < 10)
{
int r = (rand() % 100) + 1;
cout << r <<" | ";
}
return 0;
}
Random Number
42 | 68 | 35 | 1 | 70 | 25 | 79 | 59 | 63 | 65 |
However, the Numbers generated by the rand() are not rendom because it generates the sam sequence each time the code executed. so, if we run the code again and again, we'll get the same sequence repeated as in the previous run. To make a different sequence of numbers, we should specify a Seed as argument to a srand() function as shown in the given example.
srand(54545);
We will get the different sequence of numbers by using the srand() , however, the sequence will still be repeated each time the code is executed. To generate a ever changing sequence , we need to feed something other than static integer to the argument of the strand() function.
The best solution is to seed the rand() function using the current time as the argument to srand(), by calling time() function from the standard C++ library, < ctime > , then, for portability, we cast an integer type:
srand((int) time(0));
The time() function returns the number of seconds since 00:00 hours, jan 1, 1970 UTC ( i.e. current Unix time stamp ). this ensures the number generated by rand() will now seems to be truly random unless it is called again within the same second.
/*Random Number: InfoBrother:*/
#include <iostream>
#include <cstdlib> //required for rand() function:
#include <ctime> //required for time function:
using namespace std;
main()
{
srand((int)time(0));
int i = 0;
while(i++ < 10)
{
int r = (rand() % 100) + 1;
cout << r << " | ";
}
return 0;
}
Random Numbers
87 | 30 | 65 | 13 | 99 | 94 | 34 | 46 | 48 | 69 |