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
- int a = 2;
- int b = 4;
- double c = a / b;
- qDebug() << c; // result got is 0 !
Solutions
The correct answer can be obtained by the following code snippets:
- Using C style cast (not recommended)
- double c = (double) a / b;
- qDebug() << c; // result is 0.5
- Using function style cast:
- double c = double(a) / b;
- 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:
- double c = static_cast<double>(a) / b;

