Page 59 - Programming the Photon Getting Started With the Internet of Things
P. 59

anywhere within the whole program, this means you need to understand your program in
        order to know what happened to the variable. Sometimes it is much easier to debug when
        you only use that variable within its own scope.






        Floats


        All the examples that we have used thus far have included int variables. Integer variables
        are by far the most commonly used type; however, there are others that you should be

        familiar with.

             One  type  that  will  become  more  relevant  later  on  in  this  book  is  floats.  A  good
        example is the conversion of temperature when using temperature sensors. The variable

        type is a number that may consist of a decimal place for more precise measurements such
        as 1.6. Take a look at the following formula:


        f = c * 9 / 5 + 32


        This formula is the calculation for converting temperature from degrees Celsius to degrees
        Fahrenheit. If we give c the value of 23, then f will be 23 * 9 / 5 + 32 or 73.4. If we set f as
        an integer, then the value will return 73.


             Note the order in which the calculation is in. If we are not careful in the order in which
        we  calculate,  things  may  turn  out  differently  when  using  integers.  For  example,  this
        formula:


        f = (c / 5) * 9 + 32


        would result in the following:


               23 is divided by 5, which returns 4.6, which is then rounded down to 4.

               4 is then multiplied by 9 and 32 is added to give a result of 68, which is way off our
               actual temperature value of 73.4.


        For  situations  like  this,  we  use  floats;  in  the  following  example  our  temperature

        conversion function is rewritten to use floats:

        float centToFaren (float c)

        {
                   float f = c * 9.0 / 5.0 + 32.0;
                   return f;
        }


        We  have  also  added  .0  to  the  end  of  each  value—this  way  our  compiler  knows  that  it
        should treat the values as floats and not integers.
   54   55   56   57   58   59   60   61   62   63   64