C Language Problem Please Explain If int n1 5 and int d1 2
C Language Problem
Please Explain
If int n1 = 5, and int d1 = 2, what are the results of the following operations? (assume double frac) frac = (double)n1/(double)d1;frac = (double)n1/d1 + 3.5; frac = (double)(n1/d1) + 2.5;Solution
Here the heart of functionality is typecasting.
What is typecasting?
Type casting is a way to convert a variable from one data type to another data type.
frac = (double)n1/(double)d1;
n1 = 5 and d1 = 2
what this (double)n1/(double)d1 does..
here typecasting is preforming so
(double)n1 = 5.000000
(double)d1 = 2.000000
frac = 5.000000/2.000000
frac = 2.500000
frac = (double)n1/d1 + 3.5;
Here only n1 is typecasted into double
so n1 is 5.000000
and d1 is 2
(double)n1/d1 + 3.5 => (5.000000 / 2) + 3.5 => 2.500000 + 3.5 => 6.000000
frac is 6.000000
frac = (double)(n1/d1) + 3.5;
here there is no typecasting between n1 and d1 ... after division is perform then typecasting is going to applied
so
(double)(n1/d1) + 3.5
(double)(5/2) + 3.5
(double)(2) + 3.5
2.000000 + 3.5
5.500000
Answer is 5.500000
