English Български

Integer Division gives 0

The Integer Division Problem

Easy to get stuck with this … when I just started learning Qt (coming from Java background), I spent a few hours trying to figure out what was wrong ! :P

  1. int a = 2;
  2. int b = 4;
  3. double c = a / b;
  4. qDebug() << c; // result got is 0 !

Solutions

The correct answer can be obtained by the following code snippets:

  • Using C style cast (not recommended)
    1. double c = (double) a / b;
    2. qDebug() << c; // result is 0.5
  • Using function style cast:
    1. double c = double(a) / b;
    2. qDebug() << c; // result is 0.5
  • Using static_cast

static_cast is a C++ type casting operator that is most commonly used to convert numeric data types:

  1. double c = static_cast<double>(a) / b;

Categories: