PDA

View Full Version : Printf formatting question


Spectre32
Dec11-04, 11:10 PM
Ok perhaps i'm not grasping how C does math. I have these few questions:

E = delta*beta/gamma+c/b

F = (d/b)%d;


The print formats for those are %2.3lf and %3d respectively. Here are the values:

delta = 4 .000
beta = 4.0
gamma = 3.0
c = 2
b = 3
d = 7


c,b,d are type int and the rest are type double. On my answer sheet they says the answers for those two are E = 5.333 and F = 2 i have the spaces down, but i'm having a problem getting to those answers.

Any help would be great.

wave
Dec12-04, 12:02 AM
E = [(delta * beta) / gamma] + (c / b) = 5.333 + 0. The result of c / b is truncated. Similarly, F = (d / b) % d = 2 % 7 = 2.

Spectre32
Dec12-04, 12:29 AM
hmmm i think i wa sjust screwing something minor then up. THanks

ceptimus
Dec12-04, 03:03 AM
you can cast the ints into doubles if you wish

... + (double) c / (double) b

actually you only need to cast one of them as when an operation involves a mixture of ints and doubles, the remaining int(s) will be promoted automatically.

However, with your formula, the c/b part is calculated first, and as they are both ints, an integer calculation is done. then the answer to that calculation is promoted to a double, so that it can be added to the other doubles.

Spectre32
Dec12-04, 07:31 AM
well see these are like test questions, and I wanted to know how to do them in the proper way. If it was up to me everything would be double.