0

I can't seem to figure this one out but I'm sure it's easy. My program seems to be truncating decimal values even though stored in a double
Both sets of code below output the number 0 when I need them to output .5, what am I doing wrong?

cout << (1/2);

double value;
value = (1/2);
cout << value;
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by siddhant3s
0

Even though you store it in a double, you are still doing integer division because both operands to the slash are integers. Add a decimal point to at least one of them to get decimals. value = 1.0 / 2;

0

Yeah, Nucleon is right.
What nucleon suggested is called implicit type conversion. The compiler in this case will convert the type of 2 from int to double. Hence the division performed will be on decimals(rather than integers).
To do a explicit type conversion, use the static_cast<type_name>(operand)
For eg:

int a=1,b=2;
//cast promotes the type of int a to double
double value = static_cast<double>(a)/static_cast<double>(b);
//you can even use cast on one operand like:
//value=static_cast<double>(a)/b; 
cout << value;

Learn about casts. Although they are evil, but you will need them in some cases.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.