user2064000
user2064000

Reputation:

Floating point numbers are printing only the integral part

I have a program like this:

#include <iostream>
using namespace std;

int main ()
{
    double x;
    for (int i = 1; i < 100; i++)
    {
        cout << (x = i/100) << endl;
    }
    return 0;
}

On running it, I only get:

0
0
0
[...]

I've tested this on both Cygwin-g++ and MinGW-g++; both version 4.7.2. Where could possibly be the problem?

Upvotes: 1

Views: 268

Answers (4)

dhein
dhein

Reputation: 6555

It is just because = is a sequence operator, and a conversion is just done within a single sequence.

So you just do integer to integer arithmetic, where no conversion is needed.

So the integer result will be casted to floating point result, but that time the floating points got already discarded. So you have to make sure in the right part of = is a floatingpoint variable used that arethmetic between floatingpoint and integer values is done and the conversion is done.

You can achieve this by typing 100.0 or 1.0.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

Change 100 to 100.0 will produce a double value:

cout << (x = i/100.0) << endl;
//                ^^

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

It's because as both i and 100 are integers, the compiler does integer division.

The easiest way to solve this is to use the double literal 100.0 instead:

cout << (x = i/100.0) << endl;

Upvotes: 6

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

You need to cast either i or 100 to double, e.g.:

cout << (x = (double)i/100) << endl;
cout << (x = static_cast<double>(i)/100) << endl;

Otherwise, since they are both int, the division is performed with ints, and only then the result is being converted to double. Of course, before the conversion, you lose everything after the floating point.

Upvotes: 1

Related Questions