Thursday, July 9, 2009

C++ Intergers and doubles?

What is the output by the following statements Assume a and b are int variables, c is a double variable, and a=13, b=5, c=17.5





a, cout%26lt;%26lt;a+b-c%26lt;%26lt;endl





b. cout%26lt;%26lt; 15/2 +c%26lt;%26lt;endl





c. a/double(b) +2*c%26lt;%26lt;endl





d. cout%26lt;%26lt; 14%3 + 6.3 +b/a%26lt;%26lt;endl





e. cout %26lt;%26lt; int(c)% 5 + a-b%26lt;%26lt;endl





f cout%26lt;%26lt;13.5/2 +4.0 * 3.5 +18 %26lt;%26lt;endl





I got .5 for a


25.0 for b


c ??????


d 13.3


e ?????


f???????





any help would be great just getting confused on the priorities of int and double.

C++ Intergers and doubles?
I tried compiling the code and I got:


a: 0.5


b: 24.5


c: 37.6


d: 8.3


e: 10


f: 38.75





for b: 15 and 2 are both ints, so 15/2 is 7. To get 7.5, it would've needed to be 15.0/2 or 15/2.0 or 15.0/2.0





for c: while a and b are both ints, b is being converted to a double before the division takes place, and int / double is a double. So, it's:


a/double(b) + 2*c


13/5.0 + 2*17.5


2.6 + 35 --%26gt; 37.6





for d: the % operator is the "modulus" operator, which is only for division with integers and results in the remainder as if you had long divided. So, 14%3 is 2. (Because 14 divided by 3 is 4 remainder 2). So:


2 + 6.3 + b/a (b/a is 5/13, which is less than 1, and int/int is still an int, so it's 0)


8.3 + 0 --%26gt; 8.3





for e: c is being converted to an int, so it's 17:


int(17.5) % 5 + a-b


17%5 + 13-5


2 + 13 - 5 --%26gt; 10





for f: 13.5/2 is a double (6.75), 4.0 * 3.5 is a double (14.0), and two doubles plus an int is a double, so:


6.75 + 14.0 + 18 --%26gt; 38.75


No comments:

Post a Comment