The scalbn() function in C is part of the standard math library <math.h> and is used to scale a floating-point number by an integral power of the base (2 raised to the exponent). This function is very useful while performing high-precision calculations where scaling by powers of 2 is required.
Syntax of scalbn() in C
double scalbn(double x, int exp);
Parameters of scalbn() in C
The scalbn() function in C takes the following parameters:
- x: The floating-point number to be scaled.
- exp: The power of 2 by which we want to scale the number x.
Return Value of scalbn() in C
The scalbn() function returns the result of multiplying x by 2 raised to the power of exp i.e. x * 2^exp.
Examples of scalbn() Function in C
The below examples demonstrate how we can use the scalbn() function in C language.
Input:
double x = 1.5
int exp = 4
Output:
The result of scaling 1.50 by 2^4 is: 24.00
Example 1
The below program demonstrates how to use the scalbn() function in C.
C
// C Program to demonstrate the scalbn() function
#include <math.h>
#include <stdio.h>
int main()
{
// initialize number and exponent
double x = 1.5;
int exp = 4;
// call scalbn() function
double result = scalbn(x, exp);
// Print the result
printf(
"The result of scaling %.2lf by 2^%d is: %.2lf\n",
x, exp, result);
return 0;
}
OutputThe result of scaling 1.50 by 2^4 is: 24.00
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2
The following program demonstrates how to scale different data types in C using the scalbn() function.
C
// C program to demonstrate the scalbn() function for
// different data types
#include <math.h>
#include <stdio.h>
int main()
{
double x1 = 1.5;
float x2 = 2.5f;
long double x3 = 3.5l;
int n = 4;
// scalbn function for double
double result1 = scalbn(x1, n);
// scalbnf function for float
float result2 = scalbnf(x2, n);
// scalbnl function for long double
long double result3 = scalbnl(x3, n);
// Print the results
printf(
"The result of scaling %.2lf by 2^%d is: %.2lf\n",
x1, n, result1);
printf("The result of scaling %.2f by 2^%d is: %.2f\n",
x2, n, result2);
printf(
"The result of scaling %.2Lf by 2^%d is: %.2Lf\n",
x3, n, result3);
return 0;
}
OutputThe result of scaling 1.50 by 2^4 is: 24.00
The result of scaling 2.50 by 2^4 is: 40.00
The result of scaling 3.50 by 2^4 is: 56.00
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: The scalbn() function in C is available in three variants to accommodate different data types: scalbn() for double, scalbnf() for float, scalbnl() for long double.