Tuesday, November 1, 2011

Floats and Doubles in C programming language

A float occupies four bytes in memory and can range from -3.4e38 to +3.4e38. If this is insufficient then C offers a double data type that occupies 8 bytes in memory and has a range from -1.7e308 to +1.7e308. A variable of type double can be declared as,
double a, population ;
If the situation demands usage of real numbers that lie even beyond the range offered by double data type, then there exists a long double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes in memory.
You would see that most of the times in C programming one is required to use either chars or ints and cases where floats, doubles or long doubles would be used are indeed rare.
Let us now write a program that puts to use all the data types that we have learnt in this chapter. Go through the following program carefully, which shows how to use these different data types. Note the format specifiers used to input and output these data types.
main( )
{
char c ;
unsigned char d ;
int i ;
unsigned int j ;
short int k ;
unsigned short int l ;
long int m ;
unsigned long int n ;
float x ;
double y ;
long double z ;
/* char */
scanf ( "%c %c", &c, &d ) ;
printf ( "%c %c", c, d ) ;
/* int */
scanf ( "%d %u", &i, &j ) ;
printf ( "%d %u", i, j ) ;
/* short int */
scanf ( "%d %u", &k, &l ) ;
printf ( "%d %u", k, l ) ;
/* long int */
scanf ( "%ld %lu", &m, &n ) ;
printf ( "%ld %lu", m, n ) ;
/* float, double, long double */
scanf ( "%f %lf %Lf", &x, &y, &z ) ;
printf ( "%f %lf %Lf", x, y, z ) ;
Chapter
}

The essence of all the data types that we have learnt so far has been captured in Figure 6.2.


No comments:

Post a Comment