Tuesday, 4 September 2012

Chapter 5 - Implementing Float

From the previous chapter we learned how to use an integer using 3 steps
  1. declaring an int
  2. initializing an int
  3. using the value stored in the int
Now with this knowledge we will make use of float(decimal) values in our program.
Float stands for decimal or floating point value. Every value stored in float contains a decimal point.
In the last chapter i did not mention that a value from one variable can be used to initialize another variable. I have implemented this concept int the code below.

/*  
 Author : Ryan Sequeira  
 Date : 4th September 2012  
 Title : prints the value of 2 variables previous and current  
*/  

#include<stdio.h>  
#include<conio.h>  

void main ()  
 {  
  float current =10.123, previous=0.0;  
  clrscr();  
  printf("The current value is : %f", current);
  previous = current;
  current = 23.344;
  getch();
  printf("\n\nThe current value is: %f \nThe previous value is: %f", current, previous);
  getch();  
 }

What we learn from this code is
  1. variables can be used to initialize other variables
  2. variables can also be re initialized anywhere in the program
Here instead of using %d we make use of  %f  for float values. 

By default float shows 4 digits after the decimal point. To limit the number of digits after the decimal point we make use of %.3f.

Here .3 means  3 values after the decimal point. Hence we can make use of values 0, 1, 2, 3 or 4 only as 4 is the upper limit and negative values are not allowed obviously.

This is all there is to be learned about float, using the three steps specified above. The next chapter will show how we can make use of both integer and float values along with mathematical operators.

Activities


  1. Use the same code to to show only 2 digits after the decimal point.
  2. Implement a code with both int and float values.

No comments:

Post a Comment