1

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?

4 Answers4

6

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;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
1

Change 100 to 100.0 will produce a double value:

cout << (x = i/100.0) << endl;
//                ^^
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

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.

dhein
  • 6,431
  • 4
  • 42
  • 74
  • `1f` is not valid C++. – Pascal Cuoq Sep 18 '13 at 11:43
  • @Pascal Cuoq sure about? I'm using pretty often in my OpenGL app which is implemented in my FLTK project (which is c++). and the MSVC compiler didn't throw any warnings untill today. (And we all know, even the MSV pure c compiler is more C++ as C) So Im a bit confused if it is so. – dhein Sep 18 '13 at 14:51
  • A particular compiler is free to accept the syntax `1f`, which can be added to the C++ language without ambiguity (and indeed, is accepted in some C-like languages such as Java). But when answering C++ question, it's best not to use it, without knowledge of the OP's compiler. http://ideone.com/vzUqw3 – Pascal Cuoq Sep 18 '13 at 15:01
  • @Pascal Cuoq ok, I'll change it, just didn't knew. – dhein Sep 18 '13 at 15:12