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.
/* 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 }
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.
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 |
Let’s try calculating the area of a circle with a = π×r2, which is PI * r * r.
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.