Data type casting
General format of data type casting: (casting data type) statement;
Example: (int) b;
Suppose you are said to write a program to do the following.
1. assign two integer values to two int variable.
2. divide one variable by another and assign this division result to a new variable.
3. print this result.
You should write the following code to satisfy the above criteria:
#include<stdio.h> int main() { int a,b; a=10; b=2; int div; div=a/b; // div = 5 printf("div = %d",div); return 0; }
OUTPUT
div = 5
Now you modify this program as follows and see the wrong output:
#include<stdio.h>
int main()
{
int a,b;
a=10;
b=3;
int div;
div=a/b; // div = 3.333333
printf("div = %d",div);
return 0;
}
OUTPUT
div = 3
Here a/b means 10/3 which is equivalent to 3.333333 and 3.33333 should assign to ‘div’ variable.But ‘div’ value is printed as 3 and fractional part has been removed. why?
pay attention, div is declared as int type variable which means it can hold only integer number such as 10, 20, -213 and so on but not any fraction such as 1.25, 3.333.
So we have to declare div as float type data. Now you got the point and re-write this code again as follows:
#include<stdio.h> int main() { int a,b; a=10; b=3; float div; div=a/b; // div = 3.333333 printf("div = %f",div); return 0; }
OUTPUT
div = 3.000000
Still wrong output. Why?
pay attention on div=a/b; Right side of assignment operator is : a/b and a,b are integer variable and a/b is also converted into integer before saving the result to a fraction type variable(div). Hence we have to enforce the result of a/b to convert as float then save it to div. To do this we have to add (float) before a/b. Now run the following code and you will see the right output.
#include<stdio.h>
int main()
{
int a,b;
a=10;
b=3;
float div;
div= (float)a/b; // div = 3.333333
printf("div = %f",div);
return 0;
}
OUTPUT
div = 3.333333
Enforcing a data type to convert into a different data type is called data type casting.
General format of data type casting: (casting data type) statement;
Next Previous