Floating-point numbers

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:

f​l​o​a​t​ ​g​;​ ​ ​ ​ ​ ​ ​ ​/​/​ ​3​2​-​b​i​t​s​
d​o​u​b​l​e​ ​h​;​ ​ ​ ​ ​ ​ ​/​/​ ​6​4​-​b​i​t​s​
l​o​n​g​ ​d​o​u​b​l​e​ ​i​;​ ​/​/​ ​1​2​8​-​b​i​t​s​

Tokens for displaying floating-point numbers

printf() can also display floating point numbers, most commonly using the tokens %f and %e. In main.c, replace the integer-related code:

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​d​o​u​b​l​e​ ​y​ ​=​ ​1​2​3​4​5​.​6​7​8​9​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​y​ ​i​s​ ​%​f​​n​"​,​ ​y​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​y​ ​i​s​ ​%​e​​n​"​,​ ​y​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

When you build and run it, you should see:

y​ ​i​s​ ​1​2​3​4​5​.​6​7​8​9​0​0​
y​ ​i​s​ ​1​.​2​3​4​5​6​8​e​+​0​4​

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:

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​d​o​u​b​l​e​ ​y​ ​=​ ​1​2​3​4​5​.​6​7​8​9​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​y​ ​i​s​ ​%​.​2​f​​n​"​,​ ​y​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​y​ ​i​s​ ​%​.​2​e​​n​"​,​ ​y​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

When you run it, you should see:

y​ ​i​s​ ​1​2​3​4​5​.​6​8​
y​ ​i​s​ ​1​.​2​3​e​+​0​4​

Functions for floating-point numbers

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:

#​i​n​c​l​u​d​e​ ​<​m​a​t​h​.​h​>​

One warning: all of the trig-related functions are done in radians, not degrees!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset