Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

Number system in c programming pdf

29/11/2021 Client: muhammad11 Deadline: 2 Day

C Programming

C programming!!!!! Expert only
Compound interest.

(a) Write a function to compute and return the amount of money, A, that you will have in n years if you invest P dollars now at annual interest rate i. Take n, i, and P as parameters. The formula is

A = P(1 + i)n

(b) Write a function to compute and return the amount of money, P, that you would need to invest now at annual interest rate i in order to have A dollars in n years. Take n, i, and A as parameters. The formula is:
P =A / (1 + i)n

(c) Write a function that will read and validate the inputs for this program. Using call by value/address, return an enumerated constant for the choice of formulas, a number of years, an interest rate, and an amount of money, in dollars. All three numbers must be greater than 0.0.

(d) Write a main program that will call the input routine to gather the data. Then, depending on the user's choice, it should call the appropriate calculation function and print the results of thecalculation.

Basic Data Types

186

Chapter 7

Using Numeric Types

Two kinds of number representations, integer and floating point, are supported by C. The various integer types in C provide exact representations of the mathematical concept of “integer” but can represent values in only a limited range. The floating-point types in C are used to represent the mathematical type “real.” They can represent real numbers over a very large range of magnitudes, but each number generally is an approximation, using a limited number of decimal places of precision.

In this chapter, we define and explain the integer and floating-point data types built into C and show how to write their literal forms and I/O formats. We discuss the range of values that can be stored in each type, how to perform reliable arithmetic computations with these values, what happens when a number is converted (or cast) from one type to another, and how to choose the proper data type for a problem.

We would like to think of numbers as integer values, not as patterns of bits in memory. This is possible most of the time when working with C because the language lets us name the numbers and compute with them symbolically. Details such as the length (in bytes) of the number and the arrangement of bits in those bytes can be ignored most of the time. However, inside the computer, the numbers are just bit patterns. This becomes evident when conditions such as integer overflow occur and a “correct” formula produces a wrong and meaningless answer. It also is evident when there is a mismatch between a conversion specifier in a format and the data to be written out. This section explains how such errors happen so that when they happen in your programs, you will understand what occurred.

7.1 Number Systems and Number Representation

Numbers are written using positional base notation; each digit in a number has a value equal to that digit times a place value, which is a power (positive or negative) of the base value. For example, the decimal (base 10) place values are the powers of 10. From the decimal point going left, these are 100 = 1, 101 = 10, 102 = 100, 103 = 1,000, and so forth. From the decimal point going right, these are 10−1 = 0.1, 10−2 = 0.01, 10−3 = 0.001, 10−4 = 0.0001, and so forth. Figure 7.1 shows the place values for binary (base 2) and hexadecimal (base 16); the chart shows those places that are relevant for a short integer. Just as base-10 notation (decimal) uses 10 digit values to represent numbers, hexadecimal uses 16 digit values. The first 10 digits are 0–9; the last six are the letters A–F. 1

7.2 Integer Types

To accommodate the widest variety of applications and computer hardware, C integers come in two varieties and up to three sizes. We refer to all of these types, collectively, as the integer types. However, more than

1The interested reader can refer to Appendix E for algorithms for converting numbers from one base to another.Figure ?? shows the decimal values of the 16 hexadecimal digits; Figure ?? shows some equivalent values in decimal and hexadecimal.

187

188 CHAPTER 7. USING NUMERIC TYPES

Place values for base 16 (hexadecimal) are shown on the left; base-2 (binary) place values are on the right. Each hexadecimal digit occupies the same memory space as four binary bits because 24 = 16.

214 16384

212 4096

210 1024

28 256

26 64

24 16

22 4

20 1

215 32768

213 8192

211 2048

29 512

27 128

25 32

23 8

21 2

163 = 4096 162 = 256 161 = 16 160 = 1

Figure 7.1. Place values.

six different names are used for these types, and many of the names can be written in more than one form. In addition, some type names have different meanings on different systems. If this sounds confusing, it is.

The full type name of an integer contains a sign specifier, a length specifier, and the keyword int. However, there are shorter versions of the names of all these types. Figure 7.2 lists the commonly used name, then the full name, and finally other variants.

A C programmer needs to know what the basic types are, how to write the names of the types needed, and how to input and output values of these types. He or she must also know which types are portable (this means that the type name always means more or less the same thing) and which types are not (because the meaning depends on the hardware).

7.2.1 Signed and Unsigned Integers

In C, integers come in varying lengths and in two underlying varieties: signed and unsigned. The difference is the interpretation of the leftmost bit in the number’s representation. For signed numbers, this bit indicates the sign of the value. For unsigned numbers, it is an ordinary magnitude bit.

Why does C bother with two kinds of integers? FORTRAN, Pascal, and Java have only signed numbers. For most purposes, signed numbers are fine. Some applications, though, seem more natural using unsigned numbers. Examples include applications where the actual pattern of bits is important, negative values are meaningless or will not occur, or one needs the extra positive range of the values.

On paper or in a computer, all the bits in an unsigned number represent part of the number itself. If the number has n bits, then the leftmost bit has a place value of 2n−1. Not so with a signed number because one bit must be used to represent the sign. The usual way that we represent a signed decimal number on paper is by putting a positive or negative sign in front of a value of a given magnitude. This representation, called sign and magnitude, was used in early computers and still is used today for floating-point numbers. However, a different representation, called two’s complement , is used for signed integers in most modern computers. In the two’s complement representation of a 2-byte signed integer, the leftmost bit position has a place value of −32768. A 1 in this position signifies a negative number. All the rest of the bit positions have positive place values, but the total is negative.

Common Name Full Name Other Acceptable Names

int signed int signed long signed long int long int signed long short signed short int short int signed short unsigned unsigned int unsigned long unsigned long int unsigned short unsigned short int

Figure 7.2. Names for integer types.

7.2. INTEGER TYPES 189

The binary representations of several signed and unsigned integers follow. Several of these values turn up frequently during debugging, so it is useful to be able to recognize them.

21 5

= 32

76 8

21 3

= 81

92

21 1

= 20

48

29 =

5 12

27 =

1 28

25 =

3 2

23 =

8

21 =

2

21 4

= 16

38 4

21 2

= 40

96

21 0

= 10

24

28 =

2 56

26 =

6 4

24 =

1 6

22 =

4

20 =

1

0� 0� 0� 0� � 1� 1� 1� 1

1� 0� 0� 0� � 1� 1� 0� 0

1� 1� 0� 0 � 1� 0� 0� 0

1� 0� 0� 0� � 1� 1� 0� 0

1� 0� 0� 0� � 1� 1� 0� 0

1� 1� 0� 0 � 1� 0� 0� 0

1� 1� 0� 0� � 1� 0� 0� 0

1� 1� 0� 0� � 1� 0� 0� 0

1� 0� 0� 0� � 1� 1� 0� 0

1� 0� 0� 0� � 1� 1� 0� 0

1� 0� 0� 0� � 1� 1� 0� 0

1 1 0� 0� � 1� 1� 0� 0

1� 0� 0� 0� � 1� 0� 0� 0

1� 0� 0� 0� � 1� 0� 0� 0

1� 0� 0� 0� � 1� 0� 0� 0

1� 0� 1� 0� � 1� 0 0 1

Interpreted as a signed short int high-order bit = -32768 32767� 10000� 1� 0� � -32768 + 32767 = -1 -32768 + 22768 = -10000� -32768 + 0 = -32768 -32768 + 1 = -32767

Interpreted as an unsigned short int high-order bit = 32768 32767� 10000� 1� 0� � +32768 + 32767 = 65535 +32768 + 22768 = 55536 +32768 + 0 = 32768 +32768 + 1 = 32769

Figure 7.3. Two’s complement representation of integers.

Since the difference in meaning between signed and unsigned numbers depends only on the first bit, a number with a 0 in the high-order position has the same interpretation whether it is signed or unsigned. However, a number with a 1 in the high-order position is negative when interpreted as a signed integer and a very large positive number when interpreted as unsigned. Several examples of positive and negative binary two’s complement representations are shown in Figure 7.3. Every unsigned 2-byte number larger than 32,767 has the same bit pattern as some negative-signed 2-byte number. For example, in most PCs, the bit patterns of 32,768 (unsigned) and −32,768 (signed) are identical.

Negation. To negate a number in two’s complement, invert (complement) all of the bits and add 1 to the result. For example, the 16-bit binary representation of +27 is 00000000 00011011, so we find the represen- tation of −27 by complementing these bits, 11111111 11100100, and then adding 1: 11111111 11100101.

You can tell whether a signed two’s complement number is positive or negative by looking at the high- order bit; if it is 1, the number is negative. To find the magnitude of a positive integer, simply add up the place values that correspond to 1 bits. To find the magnitude of a negative integer, complement the bits and add 1. For example, suppose we are given the binary number 11111111 11010010. It is negative because it starts with a 1 bit. To find the magnitude we complement these bits, 00000000 00101101; add 1 using binary addition2 , and convert to its decimal form, 00000000 00101110 = 32 + 8 + 4 + 2 = 46. So the original number is −46.

7.2.2 Short and long integers.

Integers come in two3 lengths: short and long. On most modern machines, short integers occupy 2 bytes of memory and long integers use 4 bytes. The resulting value representation ranges are shown in Figure 7.4. As you read this list, keep the following facts in mind:

• The ranges of values shown in the table are the minimum required by the ISO C standard. • On many machines the smallest negative value actually is −32,768 for short int and −2,147,483,648

for long int.

• Unsigned numbers are explained more fully in Section 15.1. 2Adding binary numbers is similar to adding decimal values, except that a carry is generated when the sum for a bit position

is 2 or greater, rather than 10 or greater, as with decimal numbers. The carry values are represented in binary and may carry over into more than one position as they can in decimal addition.

3Or three lengths, if you count type char (discussed in Chapter 8), which actually is a very short integer type.

190 CHAPTER 7. USING NUMERIC TYPES

Data Type Names of Constant Limits Range

int INT_MIN...INT_MAX Same as either long or short short int SHRT_MIN...SHRT_MAX −32,767 . . . 32,767 long int LONG_MIN...LONG_MAX −2,147, 483, 647 . . . 2,147,483,647 unsigned int 0...UINT_MAX Same as unsigned long or short unsigned short 0...USHRT_MAX 0 . . . 65,535 unsigned long 0...ULONG_MAX 0 . . . 4,294,967,295

Figure 7.4. ISO C integer representations.

• On PCs, int usually is the same as short int. On workstations and larger machines, it is the same as long int.

• The constants INT_MIN, INT_MAX, and the like are defined in every C implementation in the header file limits.h. This header file is required by the C standard, but its contents can be different from one installation to the next. It lists all of the hardware-dependent system parameters that relate to integer data types, including the largest and smallest values of each data type supported by the local system.

The type int is tricky. It is defined by the C standard as “not longer than long and not shorter than short.” The intention is that int should be the same as either long or short, whichever is handled more efficiently by the hardware. Therefore, many C systems on Intel 80x86 machines implement type int as short.4 We refer to this as the 2-byte int model. Larger machines implement int as long, which we refer to as the 4-byte int model.

The potential changes in the limits of an int, shown in Figure 7.4, can make writing portable code a nightmare for the inexperienced person. Therefore, it might seem a good idea to avoid type int altogether and use only short and long. However, this is impractical, because the integer functions in the C libraries are written to use int arguments and return int results. The responsible programmer simply must be aware of the situation, make no assumptions if possible, and use short and long when it is important.

Integer literals. An integer literal constant does not contain a sign or a decimal point. If a number is preceded by a - sign or a + sign, the sign is interpreted as a unary operator, not as a part of the number. When you write a literal, you may add a type specifier, L, U, or UL on the end to indicate that you need a long, an unsigned, or an unsigned long value, respectively. (This letter is not the same as the conversion specifier of an I/O format.) If you do not include such a type code, the compiler will choose between int, unsigned, long, and unsigned long, whichever is the shortest representation that has a range large enough for your number. Figure 7.5 shows examples of various types of integer literals. Note that no commas are allowed in any of the literals.

7.3 Floating-Point Types in C

In traditional scientific notation, a real number, N , is represented by a signed mantissa, m, multiplied by a base, b, raised to some signed exponent, x; that is,

N = ±m× b ±x

For example, we might write 1.4142 × 10−2. A floating-point number is represented similarly inside the computer by a sign bit, a mantissa, and a signed exponent.

7.3.1 Representation of Real Numbers

Each of the components of a real number is stored in some binary format. The IEEE (Institute for Electrical and Electronic Engineers) established a standard for floating-point representation and arithmetic that has

4However, the Gnu C compiler running under the Linux operating system on the same machine implements type int as long.

7.3. FLOATING-POINT TYPES IN C 191

In this table, we assume that the type int is the same length as short, and that the maximum repre- sentable int is 32,767.

Literal Type Reason for Type

0 int Number is less than 32,767 200 int Number is less than 32,767

255U unsigned It uses the U code 255L long It uses the L code 255UL unsigned long It uses the UL code 32767 int Largest possible 2-byte int 32767L long It uses the L code 32768 unsigned Too large for a 2-byte signed int 65536 long Too large for a 2-byte unsigned int

3000000000 unsigned long 3 billion, too large for long 6000000000 Compile-time error 6 billion, too large for any integer type

Figure 7.5. Integer literals in base 10.

been carefully designed to give predictable results with as much precision as possible. Most scientists doing serious numerical computations use systems that implement the IEEE standard. Figure 7.6 shows the way that the number −10 is represented according to the IEEE standard for four-byte real numbers. This representation uses 32 bits divided into three fields to represent a real value. The base, b = 2, is not represented explicitly; it is built into the computer’s floating-point hardware.

The mantissa is represented using the sign and magnitude format. The sign of the mantissa (which is also the sign of the number) is encoded in a single bit, bit 31, in a manner similar to that used for integers: a 0 for positive numbers or a 1 for negative values. The magnitude of the mantissa is separated from the sign, as indicated in Figure 7.6, and occupies the right end of the number.

After every calculation, the mantissa of the result is normalized ; that means it is returned to the form 1.XX . . .X, where each X represents a one or a zero. The mantissa is shifted right or left so that exactly one nonzero bit remains to the left of the decimal point. The exponent is adjusted appropriately; that is, incremented (or decremented) by 1 each time the mantissa is shifted left (or right) by one bit position. In this way, the significant information “floats” to the left end of the mantissa. A number always is normalized before it is stored in a memory variable. Since all mantissas follow this rule, the 1 and the decimal point do not need to be stored explicitly; they are built into the hardware instead. Thus the 23 bits in the mantissa of an IEEE real number are used to store the 23 X bits. For example, in Figure 7.6, the value 0.25, or 0.01 in binary, is stored in the mantissa bits and the leading 1 is recreated by the hardware when the value is brought from memory into a register.

The number −10 is shown in binary IEEE format for type float.

1–10.0 = –1.25 × 23 = 1.1000001 0 0100000 00000000 00000000 31 30 ... 23 22 ... 0

sign exponent mantissa

• The sign bit is 1, indicating a negative number • The exponent 10000010 is represented in excess 127 notation, which means that we must subtract 127

from the binary number shown to get the true exponent: 130− 127 = 3 • The mantissa is 1.01000. . . , which means 1 + 1/4 = 1.25

Figure 7.6. Binary representation of reals.

192 CHAPTER 7. USING NUMERIC TYPES

These are the minimum value ranges for the IEEE floating-point types. The names given in this table are the ones defined by the C standard.

Type Digits of Name of Minimum Value Range

Name Precision C Constant Required by IEEE Standard

float 6 ±FLT_MIN. . .±FLT_MAX ±1.175E−38 . . . ±3.402E+38 double 15 ±DBL_MIN. . .±DBL_MAX ±2.225E−308 . . . ±1.797E+308

Figure 7.7. IEEE floating-point types.

When we add or subtract real numbers on paper, the first step is to line up the decimal points of the numbers. A computer using floating-point arithmetic must start with a corresponding operation, denormal- ization. To add or subtract two numbers with different exponents, the bits in the mantissa of the operand with the smaller exponent must be denormalized: The mantissa bits are shifted rightward and the expo- nent is increased by 1 for each shifted bit position. The shifting process ends when the exponent equals the exponent of the larger operand. We call this number representation floating point because the computer hardware automatically “floats” the mantissa to the appropriate position for each addition or subtraction operation.

The precision of a floating-point number is the number of digits that are mathematically correct. Pre- cision directly depends on the number of bits used to store the mantissa and the amount of error that may accumulate due to round-off during computations. Typically a calculation is performed using a few addi- tional bits beyond the lengths of the original operands. The final result then must be rounded off to return it to the length of the operands involved. The different floating-point types use different numbers of bits in the mantissa to achieve different levels of precision. Typical limits are given in Figure 7.7.

The exponent is represented in bits 23 . . . 30, which are between the sign and the mantissa. Each time the mantissa is shifted right or left, the exponent is adjusted to preserve the value of the number. A shift of one bit position causes the exponent to be increased or decreased by 1. In the IEEE standard real format, the exponent is stored in excess 127 notation. Here, the entire 8 bits are treated as a positive value, then the excess value, 127, is subtracted from the 8-bit value to determine the true exponent. In Figure 7.6, 127 + 3 = 130, which is the value stored in the eight exponent bits. While this format may be complicated to understand, it has advantages in developing hardware to do quick comparisons and calculations with real numbers.

C has a great variety of integer types. Fortunately, the set of floating-point types is not so extensive. There are only three: float, double, and long double. We use the terms float or floating point to refer to a variable of any of these types. There are no unsigned floating-point types. The only real difference among the types is the number of bits used in the representation, which directly affects the range and number of possible digits of precision. Figure 7.7 shows the minimum properties of the float and double types defined by the IEEE standard,5 which many C implementations support.

An IEEE float needs at least 8 bits for the exponent and 24 for the mantissa. Because of this limited number of bits, many values cannot be stored as type float with adequate precision for common numerical computations. An IEEE double uses 11 bits for the exponent and 53 for the mantissa, increasing both the range of exponents and the precision. This is a minimum standard; the actual range of real values supported by hardware may be greater than this standard requires, due to slight variations in the way the hardware and software treat floating-point numbers.6 The actual precision and exponent range for a local implementation can be found in the local version of the file float.h. The third floating-point type, long double, is new in ISO C and identical to double on most systems. The standards do not define a minimum length for it, although 12 bytes are used on some systems. Since double is sufficient for most calculations and few machines have the specialized hardware to support long double, the longer type is rarely used. All the computations in this book will use the standard float and double types.

Floating-point literals. In traditional mathematical notation, we write real numbers in one of two ways. The simplest notation is a series of digits containing a decimal point, like 672.01. The other notation, called

5The ISO C standard is less demanding than the IEEE standard. 6In our C system, both the range and the precision are slightly larger than the IEEE standard requires.

7.4. READING AND WRITING NUMBERS 193

Literal Type Size in Common Implementations

3.14 double 8 bytes 1.05792e+05 double 8 bytes 65536E-4f float 4 bytes 1.01F float 4 bytes .02l long double 8, 10, or 12 bytes 171.L long double 8, 10, or 12 bytes

Figure 7.8. Floating-point literal examples

base-10 scientific notation, uses a base-10 exponent in conjunction with a mantissa: we write 672.01 as 6.7201× 102.

In C, real literals also can be written in either decimal or a variant of scientific notation: we write 6.7201E+02 instead of 6.7201× 102. A numeric literal that contains either a decimal point or an exponent is interpreted as one of the floating-point types; the default type is double. (A literal number that has no decimal point and no exponent is an integer.) There are several rules for writing literal constants of floating-point types:

1. You may write the number in everyday decimal notation: Any number with a decimal point is a floating-point literal. The number may start or end with the decimal point; for example, 1.0, 0.1, 1. .1416, or 120.1,.

2. You may use scientific notation. When you do so, write a mantissa part followed by an exponent part; for example, 4.50E+6. The mantissa part follows the rules for decimal notation, except that it is not necessary to write a decimal point. Examples of legal mantissas are 3.1416, 341.0, .123, and 89.

The exponent part has a letter followed by an optional sign and then a number.

• The letter can be E or e. • The sign can be +, -, or it can be omitted (in which case, + is assumed). • The exponent number is an integer of one to three digits in the proper ranges, as given in Fig-

ure 7.7. If your system does not follow the standard, the ranges may be different.

3. Following the literal value a floating-point type-specifier may be used, just as for integers. (This letter is not the same as the conversion specifier of an I/O format.) The specifiers f and F designate a float, while l and L designate a long double. If a floating-point literal has no type specifier, it is a double.

Figure 7.8 shows some examples of floating-point literals and the actual number of bytes used to store them.

7.4 Reading and Writing Numbers

Two factors must be considered when choosing a format for reading a number: the type of the variable in which the value will be stored and the way the value appears in the input. Similarly, when printing a number, its type and the desired output format must be considered. In previous examples, we used only a few of the many possible formats for numeric input and output, which we now discuss.

7.4.1 Integer Input

Each type of value requires a different I/O conversion specifier in the format string. An integer conversion specifier starts with a % sign, followed by an optional field-width specifier (output only), and a code for the

194 CHAPTER 7. USING NUMERIC TYPES

Context Conversion Meaning and Use

scanf() %d Read a base-10 (decimal) signed integer (traditional C and ISO C) %i Read a decimal or hexadecimal signed integer (ISO C only) %u Read a decimal unsigned integer (traditional C and ISO C)

%hi or %hd or %hu Use a leading h for short int %li or %ld or %lu Use a leading l for long int

printf() %d Print a signed integer in base 10 %i Same as %d for output %u Print an unsigned integer in base 10

%hi or %hd or %hu Use a leading h for short int %li or %ld or %lu Use a leading l for long int

Note: The code for short integers is h instead of s, because s is used for strings (see Chapter 12).

Figure 7.9. Integer conversion specifications.

type of value to be read or written. Figure 7.9 summarizes the options available for signed7 integers. The use of %hi and %li will be illustrated by the program in Figure 7.28.

The %i code is new in ISO C,8 supplementing the traditional %d. With %i, input numbers can be entered in either decimal or hexadecimal notation (see Chapter 15), whereas %d works only for decimal (base-10) numbers. A representational error9 will occur if an input value has more digits than the input variable can store. The faulty input will be accepted, but only a portion of it will be stored in the variable. The result is a meaningless number that will look like garbage when it is printed. When a program’s output clearly is wrong, it always is a good idea to echo the input on which it was based. Sometimes, this uncovers an inappropriate input format or a variable too short to store the required range of values.

7.4.2 Integer Output

For output, the %d and %i conversion codes can be used interchangeably. We use %i in this text because it is more mnemonic for “integer” and therefore less confusing for beginners.

When designing the output of a program, the most important things to consider are that the information be printed correctly and labeled clearly. Sometimes, however, spacing and alignment are important factors in making the output clear and readable. We can control these factors by writing a field-width specification (an integer) in the output format between the % and the conversion code (i, li, or hi). For example, %10i means that the output value is an int and the printed form should fill 10 columns, while %4hi means that the output value is a short int and the printed form should fill 4 columns. If the given width is wider than necessary, spaces will be inserted to the left of the printed value. To print the number at the left edge of the field, a minus sign is written between the % and the field width, as in %-10i. The remainder of the field is filled with blanks.10 If the width is omitted from a conversion specifier or if the given width is too small, C will use as many columns as are required to contain the information and no spaces will be inserted on either end (therefore, the effective default field width is 1). Using a field-width specifier allows us to make neat columns of numbers, as will be illustrated by the program in Figure 7.28.

Positive or negative? If an unsigned integer has a bit in the high-order position and we try to print it in a %i format instead of a %u format, the result will have a negative sign and the magnitude may even be small. Unfortunately, most programmers eventually make this careless mistake. The short program in Figure 7.10 illustrates what can happen when an inappropriate conversion specifier is used. Two unsigned numbers are printed, first properly, then with a signed format.

7Input and output for unsigned numbers will be discussed in Chapter 15, which deals with hexadecimal notation and bit-level computation on unsigned numbers.

8Older compilers may not support %i. 9Other sources of representational error will be discussed in Section 7.6.

10A format string may specify a nonblank character to use as a filler.

7.4. READING AND WRITING NUMBERS 195

#include

int main( void ) {

short unsigned hui = 33000; long unsigned lui= 4200000000;

printf( "%hu is a short unsigned int\n", hui); printf( " printed in hi it is: %hi\n\n", hui );

printf( "%lu is a long unsigned int\n", lui); printf( " printed in li it is: %hi\n\n", lui );

}

Figure 7.10. Incorrect conversions produce garbabe output.

33000 is a short unsigned int printed in hi it is: -32536

4200000000 is a long unsigned int printed in li it is: -5632

In both cases, it is easy to see that the output is garbage because it has a negative sign. However, using a different constant, the output is even more confusing; it is still wrong but there is no negative sign to give us a clue.

3000000000 is a long unsigned int printed in li it is: 24064

7.4.3 Floating-Point Input

In a floating-point literal constant (Figure 7.8), a letter (called the type specifier) is written on the end to tell the compiler whether to translate the constant as a float, a double, or a long double value. An input format must contain this same information, so that scanf() will know how many bytes to use when storing the input value. In a scanf() format, the input conversion specifier for type float is %g; for double, it is %lg; and for long double, it is %Lg. Figure 7.11 summarizes the basic conversion specifiers for real numbers. For input, all the basic specifiers %g, %f, and %e have the same meaning and can be used interchangeably, although the current convention is to use %g.

The actual input value may be of large or small magnitude, contain a decimal point or not, and be any number of decimal digits long. The number will be converted to a floating-point value using the number of bytes appropriate for the local C translator. (Commonly, this is 4 bytes for %g, 8 bytes for %lg, and 8 bytes or more for %Lg.) However, sometimes, the number stored in the variable is not exactly the same as the input given. This happens whenever the input, when converted to binary floating-point notation, has more digits of precision (possibly infinitely repeating) than the variable can store. In this case, only the most significant digits are retained, giving the closest possible approximation.

7.4.4 Floating-Point Output

Output formats for real numbers are more complex than those of integers because they have to control not only the field width but also the form of the output and the number of significant digits printed. There are three basic choices of conversions: %f, %e, and %g. The %f conversion prints the value in ordinary decimal form, the %e conversion prints it in scientific notation, and the %g conversion tries to choose the “best” way to present the number. This may be similar to %f, %e, or even %i, depending on the size of the number relative to the specified field width and precision. Whatever precision is specified and whatever conversion code is used, floating-point numbers will be rounded to the last position printed.11

11Note that this is different from the rule for converting a real number to an integer, which will be discussed later in this chapter. During type conversion, the number is truncated, not rounded.

196 CHAPTER 7. USING NUMERIC TYPES

Context Conversion Meaning and Usage

scanf() %g, %f, or %e Read a number and store in a float variable %lg, %lf, or %le Read a number and store in a double variable %Lg, %Lf, or %Le Read a number and store in a long double variable

printf() %f Print a float or a double in decimal format %e Print a float or a double in exponential format %g Print a float or a double in general format

Figure 7.11. Basic floating-point conversion specifications.

All three kinds of conversion specifiers (%f, %e, and %g) can include two additional specifications: the total field width (as described for an integer) and a precision specifier. These two numbers are written between the % and the letter, separated by a period, as in %10.3f. In addition, either the total field width or the precision specifier can be used alone, as in %10f or %.3f. The default precision is 6, and the default field width is 1 (as it is for integers). If the field is wider than necessary, the unused portion will be filled with blank spaces.

The %f and %e conversions. For the %f and %e conversions, the precision specifier is the number of digits that will be printed after the decimal point. When using the %f conversion, numbers are printed in ordinary decimal notation. For example, %10.3f means a field 10 spaces wide, with a decimal point in the seventh place, followed by three digits. An example is given in Figure 7.12.

In a %e specification, the mantissa is normalized so that it has exactly one decimal digit before the decimal point, and the last four or five columns of the output field are occupied by an exponent (an example is given in Figure 7.13). For a specification such as %.3e, one digit is printed before the decimal point and three are printed after it, so a total of four significant digits will be printed.

The %g conversion tries to be smart. The result of a %g conversion can look like an integer or the result of either a %f or %e conversion. The precision specifier determines the maximum number of significant digits that will be printed. The printf() function first converts the binary numeric value to decimal form, then it uses the following rules to decide which output format to use. Here, assume that, for a number N , with D digits before the decimal point, the precision specifier is S.

• If D == S, the value will be rounded to the nearest integer and printed as an integer (an example is given in Figure 7.14).

• If D > S, the number will be printed in exponential format, with one digit before the decimal point and S − 1 digits after it (an example is given in Figure 7.15).

–167.2476 Printed using %10.3f field specifier: -167.248

Seven columns with two leading blanks Three columns, rounded

10 columns total

Figure 7.12. The %f output conversion.

–167.2476 Printed using %10.3e field specifier: -1.672e+02

3 columns, rounded

10 columns total

Figure 7.13. The %e output conversion.

7.4. READING AND WRITING NUMBERS 197

–167.2476 Printed using %10.3g field specifier: -167

10 columns total with three digits of precision.

Figure 7.14. Sometimes %g output looks like an integer.

• If D < S and the exponent is less than −4, the number will be printed in exponential format, with one digit before the decimal point and S − 1 digits after it (an example is given in Figure 7.16).

• If D < S and the exponent is −4 or greater, the number will be printed in decimal format with D digits before the decimal point and S −D digits after it (an example is given in Figure 7.17).

In all four cases, the precision specifier determines the total number of significant digits printed, including any nonzero digits before the decimal point. Therefore, %.3g will print one less significant digit than %.3e, which always prints three digits after the decimal point. Also, %.3g may print several digits fewer than %.3f.

Finally, the %g conversion strips off any trailing zeros or decimal point that the other two formats will print. Therefore, the number of places printed after the decimal point is irregular. This leads to an important rule: The %g conversion is not appropriate for printing tables. Usually %f is used for tables, unless the values are of very large magnitude.

7.4.5 One Number may Appear in Many Ways

Figure 7.18 shows how the input values of 32.1786594, 2.3, and 12345678 might look if they were read into a float variable, and then printed in a variety of formats. Each input was read using scanf() with the %g specifier. The actual converted value stored in a float variable is shown beneath that. Output of these values was produced by printf(), using the conversion formats shown.

Notes on Figure 7.18. Output conversion specifiers. When examining the various results, note the following details:

First line. This line shows the values entered from the keyboard. In the first column, we input more than the six or seven significant digits that a float variable can store; the result is that the last digits of the internal value (on the next line) are only an approximation of the input.

Second line. This line shows the actual values stored in three float variables. Due to the limited number of bits, the first two values cannot be represented exactly inside the computer. This may not seem surprising for the first value, since a float has only six digits of precision, but even the value of 2.3 is not represented

–1672.476 Printed using %10.3g field specifier: -1.67e+03

Three digits of precision, rounded

10 columns total

Figure 7.15. Sometimes %g looks like %e.

-1.67e-05

3 digits of precision, rounded

10 columns total

-.000016724 printed using %10.3g field specifier: }

Figure 7.16. For tiny numbers, %g looks like %e.

198 CHAPTER 7. USING NUMERIC TYPES

–167.2476 Printed using %10g field specifier: (The default precision = 6)

-167.248

Seven columns with two leading blanks Three columns, rounded

Figure 7.17. Sometimes %g looks like %f.

exactly. This is because, just as there are repeating fractions in the decimal system (like 1/7), when certain decimal values are converted into their binary representation, the result is a repeating binary fraction. The stored internal value of 2.3 is the result of truncating this repeating bit sequence. By chance, even though it is more than six digits long, the third value, 12345678, could be represented exactly. Even though the stated level of precision is six decimal digits, longer numbers sometimes can be represented exactly, while some shorter ones can only be approximated.

Main portion of table.

1. All output values are rounded to the last place that is printed.

2. An output too wide for the field is printed anyway, it just overflows its boundary, as in some of the values in the last column.

3. The default output precision is six decimal places, so you get six digits after the decimal point with %f and %e unless you ask for more or fewer. With %g, you get a maximum of six significant digits.

4. The %g conversion specifier works similar to %f for numbers that are not too large or too small. The primary differences are that trailing zeros and trailing decimal points will not be printed and that the precision specifies significant digits, not actual digits after the decimal point. For very large and very small numbers, %g works almost like %e except that one fewer significant digit will be printed. Therefore, the number 12345678 printed in %.3e becomes 1.235e+07, but printed in %.3g, it is 1.23e+07.

The programs in Figures 7.21 and 7.28 illustrate some ways in which format specifiers can be used to achieve desired output results. To get a good sense of what the C language does with different floating-point types, experiment with various input values and changing the formats in these programs.

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

A Grade Exams
Math Exam Success
Isabella K.
Essay & Assignment Help
Peter O.
Engineering Guru
Writer Writer Name Offer Chat
A Grade Exams

ONLINE

A Grade Exams

Being a Ph.D. in the Business field, I have been doing academic writing for the past 7 years and have a good command over writing research papers, essay, dissertations and all kinds of academic writing and proofreading.

$24 Chat With Writer
Math Exam Success

ONLINE

Math Exam Success

I am an elite class writer with more than 6 years of experience as an academic writer. I will provide you the 100 percent original and plagiarism-free content.

$25 Chat With Writer
Isabella K.

ONLINE

Isabella K.

I am a professional and experienced writer and I have written research reports, proposals, essays, thesis and dissertations on a variety of topics.

$41 Chat With Writer
Essay & Assignment Help

ONLINE

Essay & Assignment Help

I am an experienced researcher here with master education. After reading your posting, I feel, you need an expert research writer to complete your project.Thank You

$16 Chat With Writer
Peter O.

ONLINE

Peter O.

Being a Ph.D. in the Business field, I have been doing academic writing for the past 7 years and have a good command over writing research papers, essay, dissertations and all kinds of academic writing and proofreading.

$23 Chat With Writer
Engineering Guru

ONLINE

Engineering Guru

I find your project quite stimulating and related to my profession. I can surely contribute you with your project.

$50 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Creating shared value hbr - Master Public Policy Class Annotated reading #1 and 2 - Personal finance edition garman and forgue - Https xlitemprod pearsoncmg com api v1 print math - British international school new york - Identify the music of claude debussy - Executive Summary Report - 5016_ASS 2 # DRAFT 1 # Assessment 2 Instructions: Demand Management Plan # MBA-FPX5016 Operations Mgmt For Leaders - Week 1 Assignment Supporting Diversity through 21st Century Teaching and Learning - Business management ee examples - Deep Web and phishing - Itil certification management board icmb - Who is somax in ransom - Uq bookshop st lucia opening hours - Microsoft's search case study summary - Ernest van den haag on deterrence and the death penalty - Vitovalor 300 p cost - Leadership discussion Clinicals - Will centrelink prosecute me - Baking soda and hydrochloric acid lab - Penetration testing - Carlingford high school japanese - Personal Manifesto - Critical review or analytical review - Hess's law virtual lab - The inner osteogenic layer consists primarily of - Englisch hilfen simple past - First cut domain class diagram - Latrobe referencing apa 7 - How is the determination of melting point useful - Bon voyage french 1 - Types of hazards in caregiving - Hr discussion - Worldcom case study questions answers - Define lactate inflection point - Security architecture 4 - Gatic covers and frames - Thai tea mix target - An example of ethos - Group properties roles norms status size cohesiveness and diversity - Texas political culture essay - Concrete mixing lab report - Nursing Statistics - Excel qm add in 2007 - Cisco mcs 7825 i3 - What is rms number - Perceptions image boutique & skin yelp - Any Topic Relevant to an Enterprise CIO - Nursing Evolution Pediatric - How to create a shopping cart in java - Health information management essay - Ieee transactions on smart grid abbreviation - +971561686603 Abortion pills in Dubai/Abu Dhabi-mifepristone & misoprostol in DUBAI - List of media codes and conventions - 9 undine street ellalong - Using pestle analysis for a restaurant - Accounting 202 final exam answers - International business communication - Ancient egyptian flying machines - Collaborative decision making through shared governance - Arrival and departure routines in childcare - Literature review proposal - Armstrong axiom drywall trim - All blues time signature - Write a 250 + word response to the questions What are the ethical challenges Uber faces in using app-based peer-to-sharing technology? - Catch 22 full text - Jay z most kings - Elements in jane eyre - Business Model Canvas (BMC) (Williams Tents and Party Supply Rentals) - Give me liberty 6th edition volume 2 pdf - Explain how research has evolved since the florence nightingale era - Certificate of insurance aami - Romeo and juliet news report assignment - Scared straight program merced ca - The ransom of mercy carter chapter summaries - Strayer university computer science - Compare and contrast karl marx and adam smith - U.S. UNIIONS - The patella rides in what anatomical landmark on the femur - How are authentication and authorization alike - Recycle bypass and purge calculations pdf - Business - Good country people discussion questions - Quiz 4 - Prepare a diagram dfd for the new system - Tania promises to buy saki's handheld game-player for $75. saki is - The Gospel of John : The visible bible - Applying Industrial Relations Principles - Solutions to exercises in introduction to logic irving copi - You ll never walk alone karaoke female version - Provide a 50-75 word discussion reply to the following post below. - Michelin fleet solutions case study answers - How to write a discussion in a chemistry lab report - What is the null factor law - Fbc h005 blood test - Prg420 - Brett davis denture clinic - Victoria halls newcastle university - Healthy People 2020 National Goals - Ram rom prom eprom eeprom pdf