Confused by behaviour

• 03-15-2010
rocketman50
Confused by behaviour
Hey guys,

I have a piece of code here that gives the wrong answer

Code:

```int a = 5; float result; float b = 10; result = a / b;```
The problem was that the result would always be an integer. I cannot understand why this is the case? the variable 'result' is declared as floating point, so why does the integer value 'a' have any affect here? Do most compilers do this or is it only g++

I managed to fix my code by type casting and adding (float) in front of the division. Is there a better, more elegant way of doing this?

Code:

```int a = 5; float result; float b = 10; result = (float) a / b;```
Many thanks,
James
• 03-15-2010
laserlight
Quote:

Originally Posted by rocketman50
the variable 'result' is declared as floating point, so why does the integer value 'a' have any affect here?

Well, you know that because of integer division, a / b has the result of 0. Clearly, you would not get 0.5 by assigning 0 to a float variable. Therefore, the answer must be to use floating point division, not integer division. Using a float variable to store the result is not enough.

Quote:

Originally Posted by rocketman50
I managed to fix my code by type casting and adding (float) in front of the division. Is there a better, more elegant way of doing this?

That is a correct solution, though you could have used a C++ specific cast to make the cast more obvious:
Code:

`result = static_cast<float>(a) / b;`
EDIT:
Hold on, I just noticed that b is of type float. Therefore, floating point division should have been applied even without the cast. Are you sure that you observed the effects of integer division?
• 03-15-2010
vart
You have some buggy compiler or you do not show the actual code

dividing int var to float results in float

Code:

```#include <iostream> int main(int argc, char* argv[]) {         int a = 5;         float result;         float b = 10;         result = a / b;         std::cout << result <<std::endl;         return 0; }```
Output
Code:

`0.5`
• 03-15-2010
rags_to_riches
Works fine in my g++
Code:

```#include <iostream> int main() {     int a = 5;     float result;     float b = 10;     result = a / b;     std::cout << "Result: " << result << std::endl;     return 0; }```
Code:

```\$ ./intdiv Result: 0.5 \$ g++ -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5646.1~2/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*\$/s/\$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 Thread model: posix gcc version 4.2.1 (Apple Inc. build 5646) (dot 1)```