Question

I have the following in C:

long long int a;
long long int b;
long long int c;
long long int d=a*b/c;

However, I want 'd' to be double. Is there a way I can multiply, divide long long int and get a double as an answer keeping up to 3 decimals as precision?

Thanks

Was it helpful?

Solution

Cast (at least) one of the long long ints to double

double d = a * (double)b / c;

OTHER TIPS

if your numbers aren't going to overflow if you do this, you can multiple everything by 1000. Also, make sure you Always multiply things before dividing by things. You can convert to a double, but it will then potentially lose information.

Since C expressions, including subexpressions, are usually evaluated without regard to the context in which they appear, the subexpression a*b/c will be evaluated using integer arithmetic, which means truncating division.

If you want to perform floating-point arithmetic on integer values, you need to convert them to a floating-point type. This should work in your case:

long long int a;
long long int b;
long long int c;
/* Assign values to a, b, and c (!) */
double d = (double)a * b / c;

Note that converting just the first operand is enough to cause both the multiplication and the division to be done in type double.

Say double d = double(a) * double(b) / double(c); to get a floating point result. (You actually only need one element to be a double to have everything promoted, but why not be explicit.) You get the usual precision of the double-precision floating point (i.e. you don't get to pick a "precision level").

Are you sure you need floating point arithmetic (i.e. does your problem require multiple scales)? Maybe fixed-point arithmetic is more appropriate for your situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top