C Programming

MORE ABOUT FLOAT AND DOUBLE VARIABLES
C displays both float and double variables to six decimal places. This does NOT refer to the precision (accuracy) of which the number is actually stored, only how many decimal places printf() uses to display these variable types.

The following program illustrates how the different data types are declared and displayed,


	#include <stdio.h>

	main()
	{
		int     sum = 100;
		char    letter = 'Z';
		float   set1 = 23.567;
		double  num2 = 11e+23;

		printf("Integer variable is %d\n", sum);
		printf("Character is %c\n", letter);
		printf("Float variable is %f\n", set1);
		printf("Double variable is %e\n", num2);
	}


	Sample program output
	Integer variable is 100
	Character variable is Z
	Float variable is 23.567000
	Double variable is 11.000000e23

To change the number of decimal places printed out for float or double variables, modify the %f or %e to include a precision value, eg,


	printf("Float variable is %.2f\n", set1 );

In this case, the use of %.2f limits the output to two decimal places, and the output now looks like

	Sample program output
	Integer variable is 100
	Character variable is Z
	Float variable is 23.56
	Double variable is 11.000000e23


SPECIAL NOTE ABOUT DATA TYPE CONVERSION
Consider the following program,


	#include <stdio.h>

	main()
	{
		int  value1 = 12, value2 = 5;
		float answer = 0;

		answer = value1 / value2;
		printf("The value of %d divided by %d is %f\n",value1,value2,answer );
	}


	Sample program output
	The value of 12 divided by 5 is 2.000000

Even though the above declaration seems to work, it is not always 100% reliable. Note how answer does not contain a proper fractional part (ie, all zero's).

To ensure that the correct result always occurs, the data type of value1 and value2 should be converted to a float type before assigning to the float variable answer. The following change illustrates how this can be done,


	answer = (float)value1 / (float)value2;


ęCopyright B Brown. 1984-1999. All rights reserved.