Learn C - C Floating-Point Type






Floating-point numbers hold values that are written with a decimal point.

The following are examples of floating-point values:

1.6    0.00018    1234.123   100.0 

The last constant is integral, but it will be stored as a floating-point value.

Floating-point numbers are often expressed as a decimal value multiplied by some power of 10, where the power of 10 is called the exponent.

The following table shows how to Express Floating-Point Numbers.

Valuewritten in C as
1.70.17E1
0.000090.9E-4
7655.1230.7655123E4
100.01.0E2

/* your weight in platinum */
#include <stdio.h>
int main(void)
{// ww w. ja v  a 2 s . c  o  m
    float weight;    /* user weight             */
    float value;     /* platinum equivalent     */
    
    printf("Please enter your weight in pounds: ");
    
    /* get input from the user                     */
    scanf("%f", &weight);
    value = 3.0 * weight;
    printf("Your weight is worth $%.2f.\n", value);
    return 0;
}

The code above generates the following result.





Floating-Point Variables

You have a choice of three types of floating-point variables, and these are shown in the following Table.

KeywordNumber of bytesRange of values
float4+/-3.4E(+/-38 )
double8+/-1.7E(+/-308)
long double12+/-1.19E(+/-4932 )

The following code defines two float point numbers.

float radius; 
double biggest; 

To write a constant of type float, you append an f to the number to distinguish it from type double.

You could initialize the previous two variables when you declare them like this:

float radius = 2.5f; 
double biggest = 123E30; 

The variable radius has the initial value 2.5, and the variable biggest is initialized to the number that corresponds to 123 followed by 30 zeroes.

To specify a long double constant, you append an uppercase or lowercase letter L.

long double huge = 1234567.98765L;

The following code shows how to float type variable declaration and initializations.


#include <stdio.h> 
main() // w w w . j  a v a  2 s.c  o m
{ 
   //variable declarations 
   float y; 

   //variable initializations 
   y = 554.21; 
   //printing variable contents to standard output 
   printf("\nThe value of float variable y is %f", y); 
} 

The code above generates the following result.





Division Using Floating-Point Values

Here's a simple example that divides one floating-point value by another and outputs the result:


    #include <stdio.h> 
      //www. j  a va2 s  .c  o m
    int main(void) 
    { 
      float length = 10.0f;               
      float part_count = 4.0f;                 // Number of equal pieces 
      float part_length = 0.0f;                
      part_length = length/part_count; 
      printf("%f can be divided into %f pieces and each part is f .\n", length, part_count, part_length); 
      return 0; 
    } 

The code above generates the following result.

Number of Decimal Places

You can specify the number of places that you want to see after the decimal point in the format specifier.

To obtain the output to two decimal places, you would write the format specifier as %.2f.

To get three decimal places, you would write %.3f.

The following code changes the printf() statement so that it will produce more suitable output:


    #include <stdio.h> 
      /*from w w  w .  j  av  a2  s.  c o m*/
    int main(void) 
    { 
      float length = 10.0f;               
      float part_count = 4.0f;                 // Number of equal pieces 
      float part_length = 0.0f;                
      part_length = length/part_count; 
  
      printf("A plank %.2f feet long can be cut into %.0f pieces %.2f feet long.\n", 
                                       length, part_count, part_length); 
      return 0; 
    } 

The code above generates the following result.

Output Field Width

You can specify the field width and the number of decimal places.

The general form of the format specifier for floating-point values can be written like this:

%[width][.precision][modifier]f

The square brackets means optional.

You can omit width or .precision or modifier or any combination of these.

The width value is an integer specifying the total number of characters in the output including spaces. And it is the output field width.

The precision value is an integer specifying the number of decimal places that are after the decimal point.

The modifier part is L when the value you are outputting is type long double, otherwise you omit it.


    #include <stdio.h> 
      //ww w . j  a va 2s.  co  m
    int main(void) 
    { 
      float length = 10.0f;               
      float part_count = 4.0f;                 // Number of equal pieces 
      float part_length = 0.0f;                
      part_length = length/part_count; 
  
      printf("A %8.2f plank foot can be cut into %5.0f pieces %6.2f feet long.\n", 
                                               length, part_count, part_length); 

      const double RENT = 3852.99;  // const-style constant 
   
      printf("*%f*\n", RENT); 
      printf("*%e*\n", RENT); 
      printf("*%4.2f*\n", RENT); 
      printf("*%3.1f*\n", RENT); 
      printf("*%10.3f*\n", RENT); 
      printf("*%10.3E*\n", RENT); 
      printf("*%+4.2f*\n", RENT); 
      printf("*%010.2f*\n", RENT); 
      return 0; 
    } 

The code above generates the following result.

precision

To create precision with floating-point numbers, adjust the conversion specifier using numbering schemes between the % sign and the f character conversion specifier.


    #include <stdio.h> 
      /* w w w  .ja  v  a  2 s. c  om*/
    int main(void) 
    { 

        printf("%.1f", 3.123456); 
        printf("\n%.2f", 3.123456); 
        printf("\n%.3f", 3.123456); 
        printf("\n%.4f", 3.123456); 
        printf("\n%.5f", 3.123456); 
        printf("\n%.6f", 3.123456); 
      return 0; 
    } 

The code above generates the following result.

Left align

When you specify the field width, the output value will be right aligned by default.

If you want the value to be left aligned in the field, just put a minus sign following the %.


    #include <stdio.h> 
      /*from  www.ja v a2s.  c om*/
    int main(void) 
    { 
      float length = 10.0f;               
      float part_count = 4.0f;                 // Number of equal pieces 
      float part_length = 0.0f;                
      part_length = length/part_count; 
  
      printf("A %-18.2f plank foot can be cut into %5.0f pieces %6.2f feet long.\n", 
                                               length, part_count, part_length); 
      return 0; 
    } 

You can specify a field width and the alignment in the field with a specification for outputting an integer value.

For example, %-15d specifies an integer value will be presented left aligned in a field width of 15 characters.

The code above generates the following result.

Example

The following code shows how to calculate the circumference and area of a circular table.


#include <stdio.h> 
  // ww  w. j  a  v a2 s.c om
int main(void) 
{ 
  float radius = 0.0f;                  // The radius of the table 
  float diameter = 12.12f;              // The diameter of the table 
  float circumference = 0.0f;           // The circumference of the table 
  float area = 0.0f;                    // The area of the table 
  float Pi = 3.14159265f; 
  
  radius = diameter/2.0f;               // Calculate the radius 
  circumference = 2.0f*Pi*radius;       // Calculate the circumference 
  area = Pi*radius*radius;              // Calculate the area 
  
  printf("\nThe circumference is %.2f", circumference); 
  printf("\nThe area is %.2f\n", area); 
  return 0; 
} 

The code above generates the following result.

Example 2

The following code uses defined constants from limit.h and float.


/*from w  ww  .  ja v a 2 s  .co m*/
#include <stdio.h>
#include <limits.h>    // integer limits
#include <float.h>     // floating-point limits
int main(void)
{
    printf("Some number limits for this system:\n");
    printf("Biggest int: %d\n", INT_MAX);
    printf("Smallest long long: %lld\n", LLONG_MIN);
    printf("One byte = %d bits on this system.\n", CHAR_BIT);
    printf("Largest double: %e\n", DBL_MAX);
    printf("Smallest normal float: %e\n", FLT_MIN);
    printf("float precision = %d digits\n", FLT_DIG);
    printf("float epsilon = %e\n", FLT_EPSILON);
    
    return 0;
}

The code above generates the following result.

Example 3

The following code displays float value in two ways.


#include <stdio.h> 
int main(void) { 
      float aboat = 32000.0; 
      double abet = 2.14e9; 
      long double dip = 5.32e-5; 
             // w ww.  ja v a 2s.c om
      printf("%f can be written %e\n", aboat, aboat); 
      // next line requires C99 or later compliance 
      printf("And it's %a in hexadecimal, powers of 2 notation\n", aboat); 
      printf("%f can be written %e\n", abet, abet); 
      printf("%Lf can be written %Le\n", dip, dip); 
   
      return 0; 
}    

The code above generates the following result.

Example 4

Read float type number for command line.


             #include <stdio.h> 
             #include <string.h>      // for strlen() prototype 
             #define DENSITY 62.4     // human density in lbs per cu ft 
             int main() 
             { /*from  w  ww .  ja v a 2 s  . c  o m*/
                 float weight, volume; 
                 int size, letters; 
                 char name[40];        // name is an array of 40 chars 
              
                 printf("Hi! What's your first name?\n"); 
                 scanf("%s", name); 
                 printf("%s, what's your weight in pounds?\n", name); 
                 scanf("%f", &weight); 
                 size = sizeof name; 
                 letters = strlen(name); 
                 volume = weight / DENSITY; 
                 printf("%s, your volume is %2.2f cubic feet.\n", name, volume); 
                 printf("first name has %d letters,\n", letters); 
                 printf("we have %d bytes to store it.\n", size); 
              
                 return 0; 
             }    

The code above generates the following result.