Topic :Introduction To Numbers in C++ Programming Language:

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;
}


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++.



In order to use these functions, we need to include the math header file <math.h>


Functions======Syntax======Purpose
Trigonometric Functions
cosdouble 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.)
sindouble 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.)
tandouble 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.)
acosdouble 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.
asindouble 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.
atandouble 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.
atan2double 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
coshdouble cosh(double x);This function is used to return the hyperbolic cosine of x. this function required one paremeter "x" representing a hyperbolic angle.
sinhdouble sinh(double x);This function is used to return the hyperbolic sine of x. This function required one parameter "x" representing a hyperbolic angle.
tanhdouble tanh(double x); This function is used to return the hyperbolic tangent of x. this function required one paremeter "x", representing a hyperbolic angle.
acoshdouble 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.
asinhdouble 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.
atanhdouble 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
expdouble 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.
frexpdouble 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.
ldexpdouble 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.
logdouble 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.
log10double 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.
modfdouble 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.
exp2double 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.
expm1double 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.
ilogbint 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.
log1pdouble 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.
log2double 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.
logbdouble 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.
scalbndouble 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.
scalblndouble 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
powdouble 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.
sqrtdouble 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.
cbrtdouble cbrt (double x); This function is used to return the cubic root of x. Need an argument whose cubit root is computed.
hypotdouble 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
erfdouble 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.
erfcdouble 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.
tgammadouble tgamma(double x);This function is used to return the gamma function of x. this function required an parameter "x" for the gamma function.
lgammadouble 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
ceildouble 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.
floordouble 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.
fmoddouble 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.
truncdouble 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.
rounddouble 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.
llroundlong 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.
rintdouble 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.
lrintlong 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.
llrintlong 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.
nearbyintdouble 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.
remquodouble 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
copysigndouble 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.
nandouble 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)
nextafterdouble 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.
nexttowarddouble 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
fdimdouble 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.
fmaxdouble 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.
fmindouble 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
fabsdouble 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.
fmadouble 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;
}


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;
}


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;
}


Now if we run the code several times, we get different number sequences.






I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement