Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ double operator+ [duplicate]

Possible Duplicates:
Incorrect floating point math?
Float compile-time calculation not happening?

Strange stuff going on today, I'm about to lose it...

#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    cout << setprecision(14);
    cout << (1/9+1/9+4/9) << endl;
}

This code outputs 0 on MSVC 9.0 x64 and x86 and on GCC 4.4 x64 and x86 (default options and strict math...). And as far as I remember, 1/9+1/9+4/9 = 6/9 = 2/3 != 0

like image 430
rubenvb Avatar asked Nov 26 '22 21:11

rubenvb


2 Answers

1/9 is zero, because 1 and 9 are integers and divided by integer division. The same applies to 4/9.

If you want to express floating-point division through arithmetic literals, you have to either use floating-point literals 1.0/9 + 1.0/9 + 4.0/9 (or 1/9. + 1/9. + 4/9. or 1.f/9 + 1.f/9 + 4.f/9) or explicitly cast one operand to the desired floating-point type (double) 1/9 + (double) 1/9 + (double) 4/9.

P.S. Finally my chance to answer this question :)

like image 182
AnT Avatar answered Dec 09 '22 10:12

AnT


Use a decimal point in your calculations to force floating point math optionally along with one of these suffixes: f l F L on your numbers. A number alone without a decimal point and without one of those suffixes is not considered a floating point literal.

C++03 2.13.3-1 on Floating literals:

A floating literal consists of an integer part, a decimal point, a fraction part, an e or E, an optionally signed integer exponent, and an optional type suffix. The integer and fraction parts both consist of a sequence of decimal (base ten) digits. Either the integer part or the fraction part (not both) can be omitted; either the decimal point or the letter e (or E) and the exponent (not both) can be omitted. The integer part, the optional decimal point and the optional fraction part form the significant part of the floating literal. The exponent, if present, indicates the power of 10 by which the significant part is to be scaled. If the scaled value is in the range of representable values for its type, the result is the scaled value if representable, else the larger or smaller representable value nearest the scaled value, chosen in an implementation-defined manner. The type of a floating literal is double unless explicitly specified by a suffix. The suffixes f and F specify float, the suffixes l and L specify long double. If the scaled value is not in the range of representable values for its type, the program is ill-formed. 18

like image 44
Brian R. Bondy Avatar answered Dec 09 '22 10:12

Brian R. Bondy