views:

83

answers:

2

I'm not quite sure why I can't do

double a = (double) my_Function(45) / 2048 / 2340 / 90;
printf("%.4f",a); // prints out 0.00

But instead I have to use one more variable as:

double a = (double) my_Function(45);
double b = a  / 2048 / 2340 / 90;
printf("%.4f",b);  // prints out the correct value
A: 

It comes down to order of operations.

You basically are doing this in the first line

double a = (double)(my_Function(45) / 2048 / 2340 / 90);
Daniel A. White
+1 but you should probably mention the corrected version: `((double)my_Function(45)) / 2048 / 2340 / 90`
Chris Lutz
Great to know this! Thanks
Robert Dalton
The type cast has higher precedence than any of the arithmetic operators.
James McNellis
Here is the list: http://www.difranco.net/cop2220/op-prec.htm
Daniel A. White
@Daniel A. White: Not true. Cast has higher precedence than division.
AndreyT
@Matt: No, I mean higher precedence. @Daniel: Look at the list; the cast clearly has higher precedence than division. Thus, in `(double) my_Function(45) / 2048`, the cast is applied to the result of `my_Function(45)`, and then the division is computed, which is the desired behavior.
James McNellis
A totally incorrect answer got accepted?
AndreyT
@AndreyT: Because I can't vote on any of these comments, I thought it was a good idea have this whole conversation 'accepted'.
Robert Dalton
+1  A: 

What does my_Function return? Perhaps your answer is less than 10^(-4).

Duracell
Actually it was a matter of order of operations, but thanks anyway!
Robert Dalton
@Robert Dalton: In both of your cases the order is the same, so no, it is not a matter of order of operations.
AndreyT
@Robert: I ran your code in my own test prog. It didn't matter about order of operations. If the answer is too small (< 10^(-4)) you will get an output of 0.0000. It will not round.
Duracell
@Robert: Try using printf("%g",a) to confirm
Andrew Edgecombe