Sams Teach Yourself C in 24 Hours (28 page)

BOOK: Sams Teach Yourself C in 24 Hours
3.66Mb size Format: txt, pdf, ePub

18: printf(“The unsigned long int of 0xFFFFFFFF is %lu.\n”, t);

19: return 0;

20: }

After the executable file 09L03.exe is created and run on my machine, the following output is displayed on the screen:

The short int of 0xFFFF is -1.

OUTPUT

The unsigned int of 0xFFFF is 65535.

The long int of 0xFFFFFFFF is -1.

The unsigned long int of 0xFFFFFFFF is 4294967295

There are four data types declared in Listing 9.3: the short int variable x, the
ANALYSIS
unsigned int variable y, the long int variable s, and the unsigned long int variable t. The four variables are initialized in lines 6–9.

To display the decimal values of x, y, s, and t, the format specifiers %hd, %u, %ld, and

%lu are used, respectively, in lines 15–18 to convert the corresponding hex numbers to decimal numbers. The output from the program in Listing 9.3 shows that values contained by x, y, s, and t have been correctly displayed on the screen.

Mathematical Functions in C

Basically, the math functions provided by the C language can be classified into three groups:

• Trigonometric and hyperbolic functions, such as acos(), cos(), and cosh().

• Exponential and logarithmic functions, such as exp(), pow(), and log10().

• Miscellaneous math functions, such as ceil(), fabs(), and floor().

You have to include the header file math.h in your C program before you can use any math functions defined in the header file.

The following two sections introduce several math functions and describe how to use them in your programs.

12 067231861x CH09 4.10.2000 11:02 AM Page 149

Working with Data Modifiers and Math Functions

149

Calling
sin()
,
cos()
, and
tan()

You may skip the following two sections if you are not a math fan, as they are not vital to understanding the C language itself. However, if you do need to make mathematical calculations, you may appreciate that C gives you this set of math functions.

For instance, given an angle x in radians, the sin expression returns the sine of the angle.

The following formula can be used to convert the value of an angle in degrees into the
9

value in radians:

radians = degree * (3.141593 / 180.0).

Here, 3.141593 is the approximate value of pi. If needed, you can use more decimal digits from pi.

Now, let’s look at the syntax of the sin(), cos(), and tan() functions.

The syntax for the sin() function is

AX

#include

double sin(double x);

YNTS
Here, the double variable x contains the value of an angle in radians. The sin() function returns the sine of x in the double data type.

The syntax for the cos() function is

AX

#include

double cos(double x);

YNTS
Here, the double variable x contains the value of an angle in radians. The cos() function returns the cosine of x in the double data type.

The syntax for the tan() function is

AX

#include

double tan(double x);

YNTS
Here, the double variable x contains the value of an angle in radians. The tan() function returns the tangent of x in the double data type.

Listing 9.4 demonstrates how to use the sin(), cos(), and tan() functions.

LISTING 9.4

Calculating Trigonometric Values with sin(), cos(), and tan()

1: /* 09L04.c: Using sin(), cos(), and tan() functions */

2: #include

3: #include

4:

continues

12 067231861x CH09 4.10.2000 11:02 AM Page 150

150

Hour 9

LISTING 9.4

continued

5: main()

6: {

7: double x;

8:

9: x = 45.0; /* 45 degree */

10: x *= 3.141593 / 180.0; /* convert to radians */

11: printf(“The sine of 45 is: %f.\n”, sin);

12: printf(“The cosine of 45 is: %f.\n”, cos);

13: printf(“The tangent of 45 is: %f.\n”, tan);

14: return 0;

15: }

The following output is displayed on the screen when the executable file 09L04.exe is executed:

The sine of 45 is: 0.707107.

OUTPUT

The cosine of 45 is: 0.707107.

The tangent of 45 is: 1.000000.

Note that the header file math.h is included in line 3, which is required by the C

ANALYSIS
math functions.

The double variable x in Listing 9.4 is initialized with 45.0 in line 9. Here, 45.0 is the value of the angle in degrees, which is converted into the corresponding value in radians in line 10.

Then, the statement in line 11 calculates the sine of x by calling the sin() function and prints out the result on the screen. Similarly, line 12 obtains the cosine of x and shows it on the screen as well. Because x contains the value of a 45-degree angle, it’s not surprising to see that both the sine and cosine values are the same, about 0.707107.

Line 13 gives the tangent value of x by using the tan() function. As you might know, the tangent of x is equal to the sine of x divided by the cosine of x. Because the sine of a 45-degree angle is the same as the cosine of a 45-degree angle, the tangent of a 45-degree angle is equal to 1. The result (in the floating-point format) of 1.000000, in the third line of the listing’s output, proves it.

To make things simpler, you could declare a variable PI initialized to 3.141593, and another variable initialized to 180.0, and use those in your calculations. Or, simply declare a single constant initialized to the result of 3.141593/180.0.

Calling
pow()
and
sqrt()

The pow() and sqrt() functions are two other useful math functions in C. Unlike some other languages, C has no intrinsic operator for raising a number to a power.

12 067231861x CH09 4.10.2000 11:02 AM Page 151

Working with Data Modifiers and Math Functions

151

The syntax for the pow() function is

AX

#include

double pow(double x, double y);

YNTS
Here, the value of the double variable x is raised to the power of y. The pow() function returns the result in the double data type.

The syntax for the sqrt() function is

AX

9

#include

double sqrt(double x);

YNTS
Here, the sqrt() function returns the non-negative square root of x in the double data type. An error occurs if x is negative.

If you pass 0.5 to the pow() function as its second argument, and x contains a non-negative value, the two expressions, pow(x, 0.5) and sqrt, are equivalent.

Now, take a look at how to call the pow() and sqrt() functions in the program shown in Listing 9.5.

LISTING 9.5

Applying the pow() and sqrt() Functions

1: /* 09L05.c: Using pow() and sqrt() functions */

2: #include

3: #include

4:

5: main()

6: {

7: double x, y, z;

8:

9: x = 64.0;

10: y = 3.0;

11: z = 0.5;

12: printf(“pow(64.0, 3.0) returns: %7.0f\n”, pow(x, y));

13: printf(“sqrt(64.0) returns: %2.0f\n”, sqrt);

14: printf(“pow(64.0, 0.5) returns: %2.0f\n”, pow(x, z));

15: return 0;

16: }

Then, the following output is displayed on the screen after the executable file 09L05.exe is executed:

pow(64.0, 3.0) returns: 262144

OUTPUT
sqrt(64.0) returns: 8

pow(64.0, 0.5) returns: 8

The three double variables in Listing 9.5, x, y, and z, are initialized with 64.0,
ANALYSIS

3.0, and 0.5, respectively, in lines 9–11.

12 067231861x CH09 4.10.2000 11:02 AM Page 152

152

Hour 9

The pow() function in line 12 takes x and y and then calculates the value of x raised to the power of y. Because the result is a double, yet I know the fractional part will be all decimal digits of 0s, the format specifier %7.0f is used in the printf() function to convert only the non-fractional part of the value. The result is shown on the screen as 262144.

In line 13, the non-negative square root of x is calculated by calling the sqrt() function.

As in line 12, the format specifier %2.0f is used in line 13 to convert the non-fractional part of the value returned from the sqrt() function because the fractional part consists of all 0s. As you see in the output, the non-negative square root of x is 8.

As I mentioned earlier, the expression pow(x, 0.5) is equivalent to the expression sqrt.

Thus, it’s no surprise to see that pow(x, z) in the statement of line 14 produces the same result as sqrt does in line 13.

All floating-point calculations, including both the float and double data types, are done in double-precision arithmetic. That is, a float data variable must be converted to a double in order to carry on the calculation.

After the calculation, the double has to be converted back to a float

before the result can be assigned to the float variable. Therefore, a float calculation may take more time.

The main reason that C supports the float data type at all is to save memory space because the double data type takes twice as much memory space for storage as the float data type does. In many cases, precision beyond what is provided by float is simply unnecessary.

Summary

In this lesson you learned the following important modifiers and math functions:

• The signed modifier can be used to declare char and int data types that are able to hold negative as well as non-negative values.

• All int variables in C are signed by default.

• The unsigned modifier can be used to declare char and int data types that are not able to hold negative values. Doing this effectively doubles the range of positive values that the variable can hold.

• The memory space taken by a data variable may be reduced or increased by using the short or long data modifier, respectively.

12 067231861x CH09 4.10.2000 11:02 AM Page 153

Working with Data Modifiers and Math Functions

153

• There is a set of C library functions, such as sin(), cos(), and tan(), that can be used to perform trigonometric or hyperbolic computations.

• There is another group of math functions in C—for example, pow()—that can perform exponential and logarithmic calculation.

• The sqrt() function returns a non-negative square root. The expression sqrt is equivalent to the pow(x, 0.5) expression, if x has a non-negative value. You cannot pass a negative value to the sqrt() function, as this will cause an error.

9

• The header file math.h must be included in your C program if you call any math functions declared in that header file.

In the next lesson you’ll learn several very important control flow statements in C.

Q&A

Q Which bit can be used as the sign bit in an integer?

A
The leftmost bit can be used as the sign bit for an integer. For instance, assume the int data type is 16 bits long. If you count the bit position from right to left, and the first bit counted is bit 0, then bit 15 is the leftmost bit that can be used as the sign bit.

Q What can the
%lu
format specifier do?

A
The %lu format specifier can be used in a printf() string to convert the corresponding argument to the unsigned long int data type. In addition, the %lu format specifier is equivalent to %Lu.

Q When do I use
short
and
long
?

A
If you need to save memory space, and you know the value of an integer data variable stays within a smaller range, you can try to use the short modifier to tell the C compiler to reduce the default memory space assigned to the variable, for instance, from 32 bits to 16 bits.

On the other hand, if a variable has to hold a number that is beyond the current range of a data type, you can use the long modifier to increase the storage space of the variable in order to hold the number.

Q Does the
sin()
function take a value in degrees or in radians?

A
Like other trigonometric math functions in C, the sin() function takes a value in radians. If you have an angle in degrees, you have to convert it into the form of radians. The formula is:

radians = degree * (3.141593 / 180.0).

12 067231861x CH09 4.10.2000 11:02 AM Page 154

154

Hour 9

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix D, “Answers to Quiz Questions and Exercises.”

Quiz

1. Given an int variable x and an unsigned int variable y, as well as x = 0x8765

and y = 0x8765, and if the leftmost bit is used as a sign bit, is x equal to y?

2. What should you do if you try to assign a large value to an int variable, but the value you assign is too large and you end up with a negative number that you didn’t expect?

3. Which format specifier, %ld or %lu, should be used to specify an unsigned long int variable?

4. What is the name of the header file you have to include if you’re calling some C

math functions from your C program?

Exercises

1. Given the following statements,

int x;

unsigned int y;

x = 0xAB78;

y = 0xAB78;

write a program to display the decimal values of x and y on the screen.

2. Write a program to measure the sizes of short int, long int, and long double on your machine.

3. Write a program to multiply two signed int variables with positive values, and display the result as a long int.

Other books

Our Kind of Love by Shane Morgan
Casting Shadows by Sophie McKenzie
An American Bulldog by Liz Stafford
In My Father's Eyes by Kat McCarthy
El mundo perdido by Michael Crichton
Scarface by Andre Norton
The New Yorker Stories by Ann Beattie
Crossroads by Irene Hannon