operate ints and doubles

Hey guys just a quick question - If i multiply an int with a double will if work out? For example will:
1
2
3
int integer = 2;
double decimal = 1.6;
double result = integer * decimal;


this cause result to equal 3.2? will c++ automatically typecast? Thanks a bunch guys for all the help you've been.
Did you enter that code into your compiler? Does it compile? Does it produce the results you expect?

Yes, it will.
in yor case result will be 3.2
If you did: int result = integer * decimal; result will be 3;

Note that in case of
1
2
3
int x = 5;
int y = 2;
double result = x / y;
result will be 2, Because both operands of operator/ in this case are integer and so integer division will be performed. If you want to get 2.5 you should cast at least one operand to double manually:
double result = static_cast<double>(x)/y;>
Last edited on
MiiNiPaa:
Question question: I've never understood the difference between:
double result = static_cast<double>(x)/y;
and
double result = double(x) / y;

Can you explain?
jlb:
My compilers been messing with me...People have compiled my code and it works but when i run it through mine it doesn't so I haven't been trusting my compiler too much for the past couple days.

MiiNiPaa:
Ok thanks, that makes sense.
My compilers been messing with me...People have compiled my code and it works but when i run it through mine it doesn't so I haven't been trusting my compiler too much for the past couple days.

Then I really suggest you get it fixed. You can't learn to program in C/C++ with a faulty compiler.
Topic archived. No new replies allowed.