Floating Point Math
So far, these lessons have processed integers values, which encompass negative and positive counting values. C language also handles floating point values, which allow you to process numbers with a decimal point and one or more digits to the right, much as a calculator does. Since the number of digits to the left or right of the decimal point is flexible, the decimal point’s position can “float” from one position to another as needed.
- Use a calculator and c = 2×π×r to calculate the circumference of a circle with a radius of 1.0.
- Use the Open Project button to open the Floating Point Calculations.side.
- Set the power switch to position 1 if it isn’t already (if applicable for your board).
- Click Run with Terminal, and compare the result from the Propeller (displayed in the SimpleIDE Terminal against your calculated result).
/* Floating Point Calculations.c Calculate and display circumference of a circle of radius = 1.0. */ #include "simpletools.h" // Include simpletools int main() // main function { float r = 1.0; // Set radius to 1.0 float c = 2.0 * PI * r; // Calculate circumference print("circumference = %f \n", c); // Display circumference }
How it Works
This program knows that PI ≈ 3.1415926… because it is defined in the simpletools library. Inside the main function, a floating point variable named r is initialized to 1.0 with float r = 1.0.
After that, the circumference is calculated with c = 2.0 * PI * r.
Then, print(“circumference = %f \n”, c) displays the floating point value stored in c. Notice the new format placeholder: %f for a floating point value.
Did You Know?
You can declare different variable types that can store different sizes and types of numbers.
signed char | -127 to 127 |
char | 0 to 255 |
int | -2,147,483,647 to 2,147,483,647 |
unsigned int | 0 to 4,294,967,295 |
long | same as int |
unsigned long | same as unsigned int |
float | approx: 3.4X10-38 to 3.4X1038 with 6 digits of precision |
Try This
Let’s try calculating the area of a circle with a = π×r2, which is PI * r * r.
- Use Save Project As to save your project as More Floating Point.side
- Modify the main loop by adding the two statements at the end of the main function shown below.
- Compare the Propeller result against your calculated result.
- Try changing the radius to 3 and repeat.
Your Turn
- Expand More Floating Point.c to calculate the volume of a sphere using v = 4/3 × π × r3.
Keep in mind that you have to use 4.0/3.0 to get the floating point version of 4/3. You can also use pow(r, 3.0) to raise r to the third power.