O_O
O_O

Reputation: 4477

Can you do arithmetic with mismatched datatypes in C?

I'm trying to compute this equation:

int n = 89;
int SUMx = 347762, SUMy = 4898, SUMxy = 19671265;
long long SUMxx = 1370329156;

printf("(float)(( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx ) = %f \n", (float)(( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx )));

SUMxx used to be int, but doing n*SUMxx overflowed, so I changed it to long long. Now it is just giving me an answer of 0.000000 where I want it to be 0.0464.

How do I accomplish this? Is there some discrepancy where I need to change the other datatypes to long long as well?

Thank you :)

Upvotes: 1

Views: 148

Answers (4)

John Sobolewski
John Sobolewski

Reputation: 4572

hmmm...

try something like this...

(((float)(SUMx * SUMy - n * SUMxy) / (float)(SUMx * SUMx - n * SUMxx)));

keep in mind that 99/100 if both are ints will give you 0... but if one of them is a decimal it will work... also I haven't checked to make sure you aren't rolling over your ints... like Tomalak said you need to make sure you aren't going past the size of your int in those multiplications or it will roll over...

Upvotes: 1

qsc
qsc

Reputation: 512

The main problem with your calculation is that you are calculating a integer type divided by an integer type and then converting this to a float. This will produce integer rounded division. The numerator and denominator should be floating point types (float or double) like so:

(float)( SUMx*SUMy - n*SUMxy ) / (float)( SUMx*SUMx - n*SUMxx )

gives 0.000391.

Then as long as the integer operators in the numerator and denominator fit inside of an int everything should be good.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490118

Unless you're feeling horribly masochistic, change them all to double, get rid of the cast to float, and be done with it.

If you are feeling masochistic, you can do individual casts in just the right places, but it's going to be more work, and the conversions between integer and floating point will probably make it slower as well.

double n = 89;
double SUMx = 347762, SUMy = 4898, SUMxy = 19671265;
double SUMxx = 1370329156;

printf("(( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx ) = %f \n", (( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx )));

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532455

You're doing integer division so anything between 0 and 1 will be truncated before you cast it to float. Cast one of the values to double (or float) before doing the arithmetic so you're using floating point arithmetic instead

int n = 89;
int SUMx = 347762, SUMy = 4898, SUMxy = 19671265;
long long SUMxx = 1370329156;

printf("(float)(( SUMx*SUMy - n*SUMxy ) / ( SUMx*SUMx - n*SUMxx ) = %f \n",
       ( SUMx*SUMy - n*SUMxy ) / (float)( SUMx*SUMx - n*SUMxx ));

Upvotes: 5

Related Questions