If you need a number with a decimal point, like 3.2, you use a floating-point number. Most programmers think of a floating-point number as a mantissa multiplied by 10 to an integer exponent. For example, 345.32 is thought of as 3.4532 x 102. And this is essentially how they are stored: a 32-bit floating number has 8 bits dedicated to holding the exponent (a signed integer) and 23 bits dedicated to holding the mantissa with the remaining 1 bit used to hold the sign.
Like integers, floating-point numbers come in several sizes. Unlike integers, floating-point numbers are always signed:
float g; // 32-bits double h; // 64-bits long double i; // 128-bits
printf() can also display floating point numbers, most commonly using the tokens %f and %e. In main.c, replace the integer-related code:
int main (int argc, const char * argv[]) { double y = 12345.6789; printf("y is %fn", y); printf("y is %en", y); return 0; }
When you build and run it, you should see:
y is 12345.678900 y is 1.234568e+04
So %f uses normal decimal notation, and %e uses scientific notation.
Notice that %f is currently showing 6 digits after the decimal point. This is often a bit much. Limit it to two digits by modifying the token:
int main (int argc, const char * argv[]) { double y = 12345.6789; printf("y is %.2fn", y); printf("y is %.2en", y); return 0; }
When you run it, you should see:
y is 12345.68 y is 1.23e+04
The operators +, -, *, and / do exactly what you would expect. If you will be doing a lot of math, you will need the math library. To see what’s in the math library, open the Terminal application on your Mac and type man math. You will get a great summary of everything in the math library: trigonometry, rounding, exponentiation, square and cube root, etc.
If you use any of these math functions in your code, be sure to include the math library header at the top that file:
#include <math.h>
One warning: all of the trig-related functions are done in radians, not degrees!