Importance of Type Conversion

Importance of Type Conversion 

We know that their are many data types in C as int, float, double, etc.
So,
try to guess output of this program.

#include<stdio.h>
void main()
{
float a;
a=7/2;
printf("Number = ",a);
}

Expected Output: Number = 3.500000
Observed Output: Number = 3.000000

This is because on right hand side both 7 and 2 are of int type.
So, variable on right hand side will be of int type by default.

If we want 3.500000 as output then we need type conversion. 
Program with Type Conversion:

#include<stdio.h>
void main()
{
float a;
a=(float)7/2;
printf("Number = ",a);
}

Expected Output: Number = 3.500000
Observed Output: Number = 3.500000

We can get an float output by:

  • Doing above operation or 
  • By default,when one of either numerator or denominator is of float data type.
  • By default, when both numerator and denominator is of float data type.


No comments:

Post a Comment