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

Chapter 7: A + B = C 83

The purpose of #include <stdlib.h> is to tell the compiler about the atoi() function. Without that line, you may see some warning or “no prototype” errors, which typically ruin your programming day.

STDLIB.H is the standard library header file, don’t you know.

Other C language functions are available for converting strings into noninteger numbers. That’s how you translate input from the keyboard into a numeric value: You must squeeze a string by using a special function (atoi) and extract a number.

So how old is this Methuselah guy, anyway?

The following program is METHUS2.C, a gradual, creeping improvement over METHUS1.C. In this version of the program, you read a string that the user types at the keyboard. That string — and it is a string, by the way — is then magically converted into a numeric value by the atoi() function. Then, that value is displayed by using the printf() function. A miracle is happening here, something that the ancients would be truly dazzled by, probably to the point of offering you food and tossing fragrant posies your way.

#include <stdio.h> #include <stdlib.h>

int main()

{

int age;

char years[8];

printf(“How old was Methuselah?”); gets(years);

age=atoi(years);

printf(“Methuselah was %d years old.\n”,age); return(0);

}

Hunt and peck the METHUS2.C source code into your editor. You can edit the original METHUS1.C source code, but be careful to save it to disk under the new name, METHUS2.C.

Compile the program. Repair any errors you may have encountered.

Run the program. The output you see may look something like this:

How old was Methuselah?26

Methuselah was 26 years old.

84

Part II: Run and Scream from Variables and Math

No, you don’t have to experiment with METHUS2.C, but I encourage you to try this

Thank goodness this book isn’t Surgery For Dummies. Unlike that sober tome, this book allows you to freely fiddle, poke, pull, experi­ ment, and have fun. Trying that with a cadaver is okay, but in Chapter 14 of Surgery For Dummies, “Finding That Pesky Appendix on Your Nephew,” it’s frowned on.

Run the METHUS2.C program again, and when the program asks you for Methuselah’s age, type the following value:

10000000000

That’s ten billion — a one with 10 zeroes and no commas. Press Enter and the output tells you that the old guy was 1,410,065,408 years old — or some other value, not what you typed. The reason is that you entered a value greater than an integer can hold. The value returned is the remainder of what you entered divided by the maximum size of an integer in your compiler.

How about typing the following value:

-64

Yes, Mr. M. could never be negative 64 years old, but the program accepts it. The reason is that integer values include negative numbers.

Here’s one you need to try:

4.5

Is the oldest human really four-and-a-half? Probably at one time. Still, the program insists that he was only four. That’s because the point­ 5 part is a fraction. Integers don’t include frac­ tions, so all the atoi() function reads is the 4.

Finally, the big experiment. Type the following as Methus’s age:

old

Yes, he was old. But when you enter old into the program, it claims that he was only zero. The reason is that the atoi() function didn’t see a number in your response. Therefore, it gener­ ates a value of zero.

In this example, the user typed 26 for the age. That was entered as a string, transformed by atoi() into an integer value and, finally, displayed by printf(). That’s how you can read in numbers from the keyboard and then fling them about in your program as numeric values. Other sections in this chapter, as well as in the rest of this book, continue to drive home this message.

Okay, legend has it that the old man was 969 when he finally (and prob­ ably happily) entered into the hereafter. But by using this program, you can really twist history (though Methuselah probably had lots of con­ temporaries who lived as long as you and I do).

If you forget the #include <stdlib.h> thing or you misspell it, a few errors may spew forth from your compiler. Normally, these errors are tame “warnings,” and the program works just the same. Regardless, get

Chapter 7: A + B = C 85

in the habit of including the stdlib thing when you use the atoi() function.

The age=atoi(years) function is how the string years is translated into a numeric value. The atoi() function examines the string and spits up a number. That number is then placed in the age variable as a numeric value.

Why not just print the string years? Well, you can. By replacing age with years and %d with %s in the final printf() function, the program dis­ plays the same message. To wit:

printf(“Methuselah was %s years old.\n”,years);

The output is the same. However, only with a numeric variable can you perform mathematical operations. Strings and math? Give up now and keep your sanity!

You and Mr. Wrinkles

Time to modify the old Methuselah program again. This time, you create the METHUS3.C source code, as shown next. As with METHUS2.C, only subtle modifications are made to the original program. Nothing new, though you’re building up to something later in this chapter.

#include <stdio.h> #include <stdlib.h>

int main()

{

int methus; int you;

char years[8];

printf(“How old are you?”); gets(years); you=atoi(years);

printf(“How old was Methuselah?”); gets(years);

methus=atoi(years);

printf(“You are %d years old.\n”,you); printf(“Methuselah was %d years old.\n”,methus); return(0);

}

Double-check your source code carefully and save the file to disk as METHUS3.C.

86

Part II: Run and Scream from Variables and Math

Compile METHUS3.C. Fix any errors that sneak into the picture.

Run the program. You’re asked two questions, and then two strings of text are displayed — something like the following:

How old are you?29

How old was Methuselah?969

You are 29 years old.

Methuselah was 969 years old.

Of course, this data is merely regurgitated. The true power of the computer is that math can be done on the values — and it’s the computer that does the math, not you. Don’t sweat it!

You’re not really 29.

Yes, the years string variable is used twice. First, it reads in your age, and then the atoi() function converts it and saves the value in the you variable. Then, years is used again for input. This strategy works because the original value was saved in another variable — a cool trick.

The METHUS3.C program has been divided into four sections. This is more of a visual organization than anything particular to the C program­ ming language. The idea is to write the program in paragraphs — or thoughts — similar to the way most people try to write English.

A Wee Bit o’ Math

Now is the time for all good programmers to do some math. No, wait! Please don’t leave. It’s cinchy stuff. The first real math explanation is several pages away.

When you do math in the C programming language, it helps to know two things: First, know which symbols — or, to be technical, unique doodads — are used to add, subtract, multiply, and divide numbers. Second, you have to know what to do with the results. Of course, you never have to do the math. That’s what the computer is for.

Basic mathematical symbols

The basic mathematical symbols are probably familiar to you already if you have been around computers a while. Here they are:

Chapter 7: A + B = C 87

Addition symbol: +

Subtraction symbol: –

Multiplication symbol: *

Division symbol: /

Incidentally, the official C language term for these dingbats is operators. These are mathematical (or arithmetic — I never know which to use) operators.

+ Addition: The addition operator is the plus sign, +. This sign is so basic that I can’t really think of anything else you would use to add two numbers:

var=value1+value2;

Here, the result of adding value1 to value2 is calculated by the computer and stored in the numeric variable var.

– Subtraction: The subtraction operator is the minus sign, –:

var=value1-value2;

Here, the result of subtracting value2 from value1 is calculated and gently stuffed into the numeric variable var.

* Multiplication: Here’s where we get weird. The multiplication operator is the asterisk — not the × character:

var=value1*value2;

In this line, the result of multiplying value1 by value2 is figured out by the computer, and the result is stored in the variable var.

/ Division: For division, the slash, /, is used; the primary reason is that the ÷ symbol is not on your keyboard:

var=value1/value2;

Here, the result of dividing value1 by value2 is calculated by the computer and stored in the variable var.

Note that in all cases, the mathematical operation is on the right side of the equal sign — something like this:

value1+value2=var;