
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Floating Point Operations and Associativity in C, C++ and Java
In C, C++, and java, we do some mathematical operations with floating point numbers. Now here we will check whether the floating point numbers are following the associativity rule or not.
The answer is NO. The floating point numbers does not follow the associativity rules in some cases. Here we will see some examples.
Example Code
#include<iostream> using namespace std; main() { float x = -500000000; float y = 500000000; float z = 1; cout << "x + (y + z) is: " << x + (y + z) << endl; cout << "(x + y) + z is "<< (x + y) + z << endl; }
Output
x + (y + z) is: 0 (x + y) + z is 1
Here, we can see the results are not same, but theoretically we can say that they will be 1 always. Now the question comes, how this is done?
In the first case x + (y + z), the (500000000 + 1) is performing. But for the floating point round off, it is converted to 500000000 again. Now by adding -500000000 with it, it becomes 0. In the second expression, the value is (-500000000 + 500000000) = 0, then add 1 so the final result is 1.
If we use the integers, then both the expression will return the same result, which is 1.
- Related Articles
- Floating point operators and associativity in Java
- Floating-point hexadecimal in Java
- Fixed Point and Floating Point Number Representations
- Decimal fixed point and floating point arithmetic in Python
- Floating-point conversion characters in Java
- Format floating point number in Java
- Operator Precedence and Associativity in C
- Floating point comparison in C++
- C++ Floating Point Manipulation
- What is the difference between integer and floating point literals in Java?
- Format floating point with Java MessageFormat
- C++ Operators with Precedence and Associativity
- What are floating point literals in C#?
- What is C Operator Precedence and Associativity?
- What are C++ Floating-Point Constants?
