Double and Long Conversion Problems

Ok, let's say I have a double and a long long int, and would like to multiply together. However, I want the result to be in the form of a long long int. Something like this:

1
2
3
4
double Double = 0.25;
long long int LongInt = 1000000000; //higher then an int (I hope :P)
long long int Result = Double*LongInt; //would this work?
std::cout<<Result; //I want this to output: 250000000 


Would this work or would it be casted to a double and then assigned to Result? If so, is there a way around this so that I can get this kind of an answer?
You can't do floating-point arithmetic without first converting all operands to floating-point types.

So yes, the result is a double converted to a 64-bit int.


Was there something not working about the code?
Well, I was wondering if it is possible for any data to be lost in the conversion from long long int to double, like if the long long int was the max positive value.
Yes, there is loss --even though it is not apparent for your example number.

The IEEE double precision (used on Intel x87 architectures) has only a 52-bit (+1) precision mantissa (plus 11 bits for the exponent and 1 bit for the sign). (The +1 is because the first bit of the mantissa is always assumed to be a one, and hence it is not actually stored.)

You should set your compiler to use long double (which is not in the C++ standard), which on PCs will give you use of the 80-bit extended double precision floating point type. It uses 64-bits for the mantissa, 15 for the exponent, and 1 for the sign. Hence, you have two bits more precision than the long long int, and no data loss.

(Be aware also that the compiler is allowed to promote your types to anything with greater precision during calculations. So even if you are using floats (single precision), the calculations may be done using the FPU's default extended double precision registers, and converted back to float when storing the result. In your case this should be a moot point.)

Hope this helps.
Got it, thanks a bunch! ^_^
Topic archived. No new replies allowed.