Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 9: How to C Numbers 113

Signed variables can be maddening and the source of frustration as far as creepy errors are concerned. It works like this: Suppose that you add 1 to a signed integer variable. If that variable already holds the value 32,767, its new value (after you add 1) is –32,768. Yes, even though you add a number, the result is negative. In that instance, you should be using an unsigned int variable type to avoid the problem.

To use an unsigned variable and skirt around the negative-number issue, you must declare your variables by using either the unsigned int or unsigned long keyword. Your C compiler may have a secret switch that allows you to always create programs by using unsigned variables; refer to the online documentation to see what it is.

How to Make a Number Float

Two scoops of ice cream. . . .

Integer variables are the workhorses in your programs, handling most of the numeric tasks. However, when you have to deal with fractions, numbers that have a decimal part, or very large values, you need a different type of numeric variable. That variable is the float.

The float keyword is used to set aside space for a variable designed to con­ tain a floating-point, or noninteger, value. Here’s the format:

float var;

The keyword float is followed by a space or a tab, and then comes the vari­ able name, var. The line ends in a semicolon.

Or, you can declare a float variable and give it a value, just as you can any other variable in C:

float var=value;

In this format, the variable var is followed by an equal sign and then a value to be assigned to it.

Float is short for floating point. That term somehow refers to the decimal point in the number. For example, the following number is a floating-point value:

123.4567

An integer variable wouldn’t cut it for this number. It could be only 123 or 124. When you have a decimal, you need a floating-point variable.

114 Part II: Run and Scream from Variables and Math

The range for floating-point numbers is quite large. With most C compilers, you can store any number in the range ±3.4 × 10–38 to ±3.4 × 1038. In English,

that’s a value between negative 340 undecillion and positive 340 undecillion. An undecillion is a 1 with 36 zeroes after it. That’s a true, Mr. Spock-size value, though most numbers you use as floats are far less.

Rules for naming variables are in Chapter 8.

Noninteger values are stored in float variables.

Even though 123 is an integer value, you can still store it in a float vari­ able. However. . . .

float variables should be used only when you need them. They require more internal storage and more PC processing time and power than inte­ gers do. If you can get by with an integer, use that type of variable instead.

“Hey, Carl, let’s write a floating-point number program!”

Suppose that you and I are these huge, bulbous-headed creatures, all slimy and green and from the planet Redmond. We fly our UFO all over the galaxy, drink blue beer, and program in C on our computers. I’m Dan. Your name is Carl.

One day, while assaulting cows in Indiana, we get into this debate:

Dan: A light-year is 5,878,000,000,000 miles long! That’s 5 trillion, 878 bil­ lion, plus change! I’m not walking that!

Carl: Nay, but it’s only a scant 483,400,000 miles from the sun to Jupiter.

That is but a fraction of a light-year.

Dan: How much of a fraction?

Carl: Well, why don’t you type the following C program and have your computer calculate the distance for you?

Dan: Wait. I’m the author of this book. You type the program, JUPITER.C, and you figure it out. Sheesh.

#include <stdio.h>

int main()

{

float lightyear=5.878E12; float jupiter=483400000; float distance;

Chapter 9: How to C Numbers 115

distance=jupiter/lightyear;

printf(“Jupiter is %f light years from the sun.\n”,distance);

return(0);

}

Enter this program into your text editor. Be careful! Check spelling, odd char­ acters, other stuff. Save the file to disk as JUPITER.C.

Compile the program. If you see any errors, fix ’em up and recompile.

Run the program. The output looks something like this:

Jupiter is 0.000082 light years from the sun.

Carl: A mere stumble!

Dan: I’m still not walking it.

You use the float keyword to declare a floating-point variable.

In scientific notation, which is how scientists sneak around the require­ ment of typing zeroes and commas, the length of a light year is written as 5.878E12. That means that the decimal in 5.878 should be shifted to the right 12 times. (The next section covers this ugly E-notation thing.)

The variable jupiter is set equal to the mean distance between Jupiter and the sun, which is 484 million miles. In the source code, that’s 4834 fol­ lowed by 5 zeroes. There’s no need to mess with scientific notation here because the compiler can eat this relatively small-size number. (Anything over 100 billion usually requires the scientific E notation; you have to refer to your compiler’s manual to check the size of its mouth.)

The distance variable contains the result of dividing the distance between the sun and Jupiter by the length of a light-year — to find out how many light-years Jupiter is from the sun. The number is extremely small.

The %f placeholder is used in the printf() function to display floatingpoint values.

The float variables are used in this program for two reasons: because of the humongous size of the numbers involved and because division usually produces a noninteger result — a number with a decimal part.

116 Part II: Run and Scream from Variables and Math

The E notation stuff

When you deal with very large and very small numbers, the old scientific E notation stuff crops up. I assume that it’s okay to discuss this subject, because if you’re interested in programs that deal with these types of numbers, you probably already have one foot in the test tube.

E notation is required in C (or even in the Excel spreadsheet) when some num­ bers get incredibly huge. Those numbers are floating-point numbers — or the floats, as you have come to know them. Integers don’t count.

When you get a number over about eight or nine digits long, it must be expressed in E notation or else the compiler doesn’t eat it. For example, take the length of a light-year in miles:

5,878,000,000,000

That’s 5 trillion, 878 billion. In C, you don’t specify the commas, so the number should be written as follows:

5878000000000

That’s 5878 followed by nine zeroes. The value is still the same; only the commas — conveniently added to break up large numbers for your human eyeballs — have been removed. And though this number is within the range of a float, if you were to compile it, the compiler would moan that it’s too large. It’s not the value that bugs the compiler — it’s the number of digits in the number.

To make the compiler understand the value, you have to express it by using fewer digits, which is where scientific notation comes in handy. Here’s the same value in E notation, as you specify it in the JUPITER.C program, from the pre­ ceding section:

5.878E12

Scientific, or E, notation uses a number in the following format:

x.xxxxEnn

The x.xxxx is a value; it’s one digit followed by a decimal point and then more digits. Then comes big E and then another value (nn). To find out the number’s true size, you have to hop the decimal point in the x.xxxx value to the right nn places. Figure 9-1 illustrates how this concept works with the light-year value.

Figure 9-1:

Scientific notation and the light year.

Chapter 9: How to C Numbers 117

5.878 E12

58.78E11

587.8 E10

5878. E9

58780. E8

587800. E7

5878000. E6

58780000. E5

587800000. E4

5878000000. E3

58780000000. E2

587800000000. E1

5878000000000. E0

5,878,000,000,000

When you enter E numbers in the compiler, use the proper E format. To dis­ play the numbers in E format with printf(), you can use the %e placeholder. To see how it works, replace the %f in the JUPITER.C program with %e, save the change to disk, recompile, and run the result. The output is in E notation, something like the following:

Jupiter is 8.223886e-05 light years from the sun.

If the E has a negative number in front of it, as shown in this example, you hop the decimal point to the left nn places, to indicate very small numbers. You would translate the preceding value into the following:

.00008223886

Scientific, or E, notation is required when numbers contain too many digits for the C compiler to eat.

A negative E number means that the value is very small. Remember to move the decimal point to the left rather than to the right when you see this type of number.

Some compilers allow you to use the %E (big E) placeholder in printf() to display scientific-notation numbers with a big E in them.

118 Part II: Run and Scream from Variables and Math

Bigger than the Float, It’s a Double!

For handling really huge numbers, C has its largest data type, the double. These types of variables can contain absolutely huge values and should be used only when you must work with those outer-space-size values or when you require a mathematical operation that must be precise.

Double variables are declared by using the double keyword. Double comes from the term double precision, which means that the numbers are twice as accurate as floats, which are also known as single-precision numbers.

What’s precision? It deals with how decimal numbers, fractions, and very small and huge numbers are stored in a computer. Keep in mind that the computer uses only ones and zeroes to store information. For integers, that’s great. For non-integers, it means that some tomfoolery must take place. That tomfool­ ery works, but it tends to get inaccurate, or “fuzzy,” after a time, especially on the details.

As an example, gawk at this number:

123.4567891234

That’s a float if I ever saw one. But if you define that value as a float variable in C, the computer can store it only as a single-precision value. It can accu­ rately hold only the first eight digits. The rest — it makes them up! To wit:

123.45678422231

The first eight digits are precise. The rest — eh? After the 8, the value gets screwy. It’s single precision in action. Double precision can be accurate to maybe 12 or 16 decimal places (but after that, it begins acting goofy as well).

The moral of this story is twofold: First, if you have to make float calculations with your computer, remember that the number can be only so accurate. After about eight digits or so, the rest of the output is meaningless. Second, if you need precise calculations, use the double type of variable. It still has its prob­ lems, but it’s more precise than the float.

You use the double keyword to declare a double-precision floating-point variable in your C programs.

If you ever print a value — 123.456, for example — and the output you see is something like 123.456001, that extra 001 is the lack of precision the computer has when it’s dealing with floating-point numbers. For the most part, any extra value that’s added is insignificant, so don’t let it bug you.

Chapter 9: How to C Numbers 119

Being accurate to eight digits is more than enough for most noninteger calculations. For sending people to Mars, however, I recommend the double. (I know that NASA reads these books intently.)

Some compilers may offer quadruple-precision numbers with their own

unique keywords and other rules and regulations.

The greater the precision, the longer it takes the computer to deal with the numbers. Don’t use more precision than you have to.

Formatting Your Zeroes

and Decimal Places

Floating-point values can sure look gross when they’re displayed by using the %f in the printf() function. Ugh. Now you have to plug your nose and plunge a little deeper into the murky waters of printf() formatting. Fortunately, this is about the only time you have to do that.

Between the % and the f, you can insert some special formatting characters. They control the printf() function’s output and may help you get rid of some excess zeroes or trim up the number that is displayed.

The following few examples show you how to trim up your numbers with printf() and avoid the cavalcade of zeroes that appears sometimes when you’re dealing with floats and doubles.

The following placeholder displays the float number by using only two deci­ mal places. It’s ideal for displaying dollar amounts. Without it, you may have $199.9500 displayed as a price — which doesn’t appease your customer’s sense of thrift any.

%.2f

If you need to display more decimal places, specify that number after the dot:

%.4f

This placeholder formats floating-point numbers to display four digits after the decimal point. If the value isn’t that small, zeroes pad out the four deci­ mal places.

The following format information tells printf() to display the number by using six digits — which includes the decimal point:

%6f

120 Part II: Run and Scream from Variables and Math

No matter how big the number is, it’s always displayed by using six digits.

Rather than leading zeroes, the number is padded on the left with spaces.

The number 123 is displayed as

123.

This line begins with two spaces, or is indented two spaces, depending on how you look at it.

Sometimes the %f may display a number that looks like this:

145000.000000

In that case, you can trim up the number by using either %.2f, which displays only two zeroes after the decimal point, or something like %6f, which limits the output to only six digits.

An alternative to messing with numbers and other characters between the % and little f is to use the %e placeholder. It displays numbers in sci­ entific format, which is usually shorter than the %f placeholder’s output.

Then there’s the %g placeholder. That thing displays a floating-point number in either the %f or %e (scientific) format, depending on which is shorter.

Yes, I know that this chapter is short on examples. But numbers are boring.

So there.

Chapter 10

Cook That C Variable

Charred, Please

In This Chapter

Using the char declaration

Assigning characters to variables

Understanding getchar() and putchar()

Treating char as a tiny integer variable

Too many C language books seem to fixate on numbers and avoid com­ pletely the other type of variable — the character, or string, variable. It’s

definitely more fun. Rather than hold values — values, bah! — character vari­ ables hold individual characters or letters of the alphabet and complete strings of text. This certainly opens the floodgates of creativity over pounding the sand with numbers.

This chapter rounds off your variable declaration journey with an official hello to the char variable, suited for storing both single characters and strings of text. In this chapter, it’s only single characters you have to worry about.

The Other Kind of Variable

Type, the char

Though I talk about both single-character and string variables, C language has only one variable type, the char, which is defined by the keyword char. And I think, though I’m not certain, that it’s pronounced “care” and not “char,” as in “charred beyond all recognition.”