Hi
There's something bothering me with my code, and I'm not sure what variable type to use as a result. I have this in my code:
My question is, will x be a double or an integer?Code:
double x;
int y;
int z;
x = y/z
Printable View
Hi
There's something bothering me with my code, and I'm not sure what variable type to use as a result. I have this in my code:
My question is, will x be a double or an integer?Code:
double x;
int y;
int z;
x = y/z
>My question is, will x be a double or an integer?
x will be a double, but the value will lack any fractional part because y / z uses integer arithmetic. To get the fractional part, use C++'s type conversion rules and cast one of the operands to double:
Code:x = static_cast<double> ( y ) / z;
I've seen different syntax somewhere - will this work as well: (float) y?
> will this work as well: (float) y?
That's a 'C' style cast, which C++ supports for the moment.
The static cast Prelude showed is the preferred way for C++
>will this work as well: (float) y?
It will, but since you're assigning to a double variable, (double)y would be better. Or you could cast z instead of y, or both. It really doesn't matter since if either operand is double, the result of the expression is double. Also see Salem's comment on C-style casting.