Learn How to Program in Cby
|
Notice the f at the end of the variable declaration: float height = 5.7f; This insures that the variable will be formatted as a floating point number. Working with MoneyFloating points work very well when you are calculating money values, particularly tax on items purchased. Let's say that we live in a state where the sales tax is 8.25% of an item's price. We can calculate the sales tax by multiplying it by the price, like this:
Then we can calculate the total cost of an item, including tax, like this:
Or, we could put both lines together and write:
Let's try this in a new script, which calculates the total cost of a book, including tax:
Notice on the line float total = 0.0f; we used 0.0f instead of an empty variable. This tells the computer to make sure it's a floating point number. Type this source code in your editor and save it as fifth.c then compile, link, and run it. You will see this output:
Now, you must admit that these figures looks ridiculous. Nobody thinks of money having so many decimal places. We need to limit our format to only two decimal places, for cents. Here's how:
The %.2f tells the computer to limit the variable to 2 decimal places, so it prints in dollars and cents. Open your fifth.c source code and add this. Then save, compile, link, and run it. Now you will get this output:
Isn't that much better? Viewer Input with FloatTo handle floating point input from the viewer, we use the scanf function and the %f format specifier. We can change how many decimal places are displayed by adjusting the %.2f to %.1f or %.3f etc. For example, ask the viewer about height:
This program will display a number with only 1 decimal place, because we have used %.1f in our printf statement. Save this source code as sixth.c then compile, link, and run it. If you answered the question with 5.6, then your output will be:
ConstantsIf you have a variable that remains the same at all times, it is called a constant. Examples of constants are: PI (3.14159), your state's sales tax (8.25% for example), or the American Revolutionary War (1776). We use a special preprocessor directive, #define to set these variables. For example, if your state's sales tax is 8.25%, you can define a constant like this:
Notice that we used CAPITAL letters for the constant's name (TAX). This is the standard convention for C programming and it tells us that the value of TAX will not change in the program. Save this source code as seventh.c then compile, link, and run it. If you answered the question with 20, then your output will be:
|
||||||||||||||||||||||||||
|
Copyright © 2001 Kristin Switala |
|||||||||||||||||||||||||||