What happen when float divides int ?

when an integer is divided by a float, what will be the data type of resulting answer. for example a=17 and b=20.0 . ans=17/20.0 . What will be the answer in this case. '0' or '0.85?
Usual Arithmetic Conversions https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx

17 is of type int, 20.0 is of type double. 17/20.0 is evaluated as double(17)/20.0
(implicit conversion of the first operand from int to double)
Last edited on
So that means 'ans' will be 0.85 ?
So that means 'ans' will be 0.85 ?

What type is ans?
See this Expression:
50+ 17/20.0 +4
What will be the data type of the Result?
1
2
3
4
5
6
7
8
#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
	 cout << "type of 50+ 17/20.0 +4  is " << typeid(50+ 17/20.0 +4).name() << '\n';
	return 0;
}


Run it. Comes out d for double using the GCC. Don't ever rely on typeid::name(), though.
Last edited on
50 + 17/20.0 + 4 is parsed as ( 50 + (17/20.0) ) + 4

Evaluated as if:
1
2
3
const double temp1 = double(17) / 20.0 ;
const double temp2 = double(50) + temp1 ;
const double result = temp2 + double(4)


More elaborate:
1
2
3
4
5
6
7
8
const double d17 = double(17) ;
const double temp1 = d17 / 20.0 ;

const double d50 = double(50) ;
const double temp2 = d50 + temp1 ;

const double d4 = double(4) ;
const double result = temp2 + d4 ;
Last edited on
What type is the variable to which the answer will be assigned? The compiler will do some automatic type conversion to make sure it gets the proper type assigned to it. Or you could typecast variables on the right side of the equation as needed to ensure the conversions are done like you want them to be done.
Topic archived. No new replies allowed.