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;

Recommended Answers

All 2 Replies

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;

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.