
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
fdim() in C++
C++ fdim() Function
The fdim() function returns the positive difference between two floating-point values.
For example, if we have two arguments, a and b, respectively, then it will return a-b if a > b, else it will return 0. This function is defined under <cmath> or <math.h> header files and supports float, double, and long double overloads.
Syntax
Here is the following syntax for fdim() function in C++. In the following syntax, data_type defines the type of data it will take as input and return.
data_type fdim(data_type value_1, data_type value_2);
Parameters
This method accepts two parameters of floating type (i.e., can accept float, double, or long double type values).
Return Value
It returns the positive difference between two floating-point values.
Example 1: Calculating Difference of Two Float Values
Here is the following example code of using fdim() function in C++, which takes two floating-point numbers as an argument and returns their difference, if it satisfies the condition (a>b).
#include <cmath> #include <iostream> using namespace std; int main() { cout << "fdim of (5.0, 2.0) is " << fdim(5.0, 2.0) << endl; // this will return positive difference cout << "fdim of (2.0, 5.0) is " << fdim(2.0, 5.0) << endl; // this will return 0 cout << "fdim of (-5.0, -2.0) is " << fdim(-5.0, -2.0) << endl; // this will return 0 cout << "fdim of (-2.0, -5.0) is " << fdim(-2.0, -5.0) << endl; // will return positive difference return 0; }
Output
fdim of (5.0, 2.0) is 3 fdim of (2.0, 5.0) is 0 fdim of (-5.0, -2.0) is 0 fdim of (-2.0, -5.0) is 3
Example 2: Using fdim() Calculating Temperature Exceedance
Here is the following simple example code, demonstrating the use of fdim() in a real-life case.
Let's assume you want to maintain your room temperature at 25 degrees Celsius, so until it maintains 25, the code will return 0, but when it starts exceeding 25 degrees, the code will return the difference of the exceeded temperature.
#include <iostream> #include <cmath> using namespace std; int main() { double room_temp = 30.0; double safe_limit = 25.0; double excess = fdim(room_temp, safe_limit); cout << "Temperature exceeds by: " << excess << " Degree C" << endl; return 0; }
Output
Temperature exceeds by: 5 Degree C