Input and Output – Part V (Formatted I/O – Floating Point Numeric Data)

We have already known what formatted input output is for integer data. Now we will see about the formatted input output for floating point numeric data. Let’s get started …

Formatted Input Output in C (Floating Point Numeric Data)

Format for floating point numeric input

%wf

Here ‘w’ is the integer number specifying the total width of the input data (including the digits before and after the decimal and the decimal itself).

For example

scanf(“%3f%4f”,&x,&y);

  • When input data length is less than the given width, values are unaltered and stored in the variables.

                   Input-

6                6.9

                  Result-

6.0 is stored in x and 6.90 is stored in y.

  • When input data length is equal to the given width, then the given values are unaltered and stored in the given variables.

Input-

                   6.4            6.03

Result-

6.4 is stored in x and 6.03 is stored in y.

  • When input data length is more than the given width, then the given values are altered and stored in the given variables as-

Input-

6.04        76.98

Result

                     6.0 is stored in x and 4.00 is stored in y.

C program to demonstrate above example is

#include<stdio.h>
#include<conio.h>
int main(){
 float a,b,c,d,e,f;
 printf("Enter six fooating point numeric value (a,b,c,d,e,f) :\n");
 scanf("%3f%4f%3f%4f%3f%4f",&a,&b,&c,&d,&e,&f);   //reading integer data in particular format 
 printf("Stored floating point numeric values for variables are\na = %f\nb = %f\nc = %f\nd = %f\ne = %f\nf = %f\n",a,b,c,d,e,f);
 getch();
 return 0;
}

Its output will be as:

Output for above program (Formatted Floating Point Intput)

Format for floating point numeric output

%w.nf

Here w is the integer number specifying the total width of the input data and n is the number of digits to be printed after the decimal point. By default 6 digits are printed after the decimal.

For example-

printf(“x=%4.1f,y=%7.2f”,x,y);

Value of variables-

9          6.9

Output:

x = 9 . 0 , y = 6 . 9 0

 

Value of variables-

36.4     2746.03

Output

x = 3 6 . 4 , y = 2 7 4 6 . 0 3

 

Value of variables-

26.342             76.985948

Output:

x = 2 6 . 3 , y = 7 6 . 9 9

C program to demonstrate above example is:

#include<stdio.h>
#include<conio.h>
int main(){
 float a=9,b=6.9,c=36.4,d=2746.03,e=26.342,f=76.985948;
 printf("Printed floating point numeric values for variables with format specifications are\na = %4.1f\nb = %7.2f\nc = %4.1f\nd = %7.2f\ne = %4.1f\nf = %7.2f\n",a,b,c,d,e,f);
 getch();
 return 0;
}

Its output will be as:

Output for above program (Formatted Floating Point Numeric Output)

 

Leave a comment