C library - fegetround() function



The C fenv library fegetround() function is a part of floating-point environment that can be used for accessing current rounding mode. This mode represent the floating point in rounded form. The usage of this function used in various field such as graphics, numerical analysis and financial calculation.

Syntax

Following is the C library syntax of the fegetround() function.

int fegetround(void);

Parameters

This function does not accept any parameter.

Return Value

This function returns the integer values which represent one of the following rounded mode −

  • FE_TONEAREST: This parameter define the round to nearest which is zero.

  • FE_DOWNWARD: This parameter define the round value toward negative infinity.

  • FE_UPWARD: This parameter define the round value toward positive infinity.

  • FE_TOWARDZERO: This parameter define the round value zero.

Example 1

Following id the basic C library program that shows the usage of fegetround() function.

#include <stdio.h>
#include <fenv.h>

int main() {
   int round_mode = fegetround();
   printf("Current rounding mode: %d\n", round_mode);
   return 0;
}

Output

The above code produces the following result −

Current rounding mode: 0

Example 2

Below the program first check the current rounding mode and print the value of it. Then, we set the parameter FE_DOWNWARD using fesetround that determine the value towards negitive infinity and display the result.

#include <stdio.h>
#include <fenv.h>

int main() {

   // Check current rounding mode
   
   int round_mode = fegetround();
   printf("Current rounding mode: %d\n", round_mode);
   
   // Set rounding mode to downward
   
   fesetround(FE_DOWNWARD);
   round_mode = fegetround();
   printf("Rounding mode after setting to FE_DOWNWARD: %d\n", round_mode);
   
   return 0;
}

Output

On execution of above code, we get the following result −

Current rounding mode: 0
Rounding mode after setting to FE_DOWNWARD: 1024

Example 3

The fegetround() accept the parameter FE_TONEAREST to perform the task of round calculation using rint function that round the paramter of accepted integer value. Finally, the output shows how the different rounding modes affect the result of the rint function.

#include <stdio.h>
#include <fenv.h>
#include <math.h>

int main() {
   // Set rounding mode to nearest
   fesetround(FE_TONEAREST);
   
   // Perform a calculation
   double result = rint(3.5);
   printf("Result with FE_TONEAREST: %f\n", result);
   
   // Change rounding mode to toward zero
   fesetround(FE_TOWARDZERO);
   
   // Perform the same calculation
   result = rint(3.5);
   printf("Result with FE_TOWARDZERO: %f\n", result);
   
   return 0;
}

Output

After executing the above code, we get the following result −

Result with FE_TONEAREST: 4.000000
Result with FE_TOWARDZERO: 3.000000
c_library_fenv_h.htm
Advertisements