CS 10V: CH 2- Variables (2.9-2.17)

¡Supera tus tareas y exámenes ahora con Quizwiz!

type casting

explicit conversion by the programmer of one type to another is known as type casting.

Debugging

Debugging is the process of determining and fixing the cause of a problem in a computer program.

function call

Invoking a function is a function call.

numeric data types

int and double are the most common numeric data types. However, several other numeric types exist. The size of integer numeric data types can vary between compilers, for reasons beyond our scope. The following table lists the sizes for numeric integer data types used in this material along with the minimum size for those data types defined by the language standard. Definition/Size/Supported number range/Std-def min size char myVar; 8 bits; -128 to 127; 8 bits short myVar; 16 bits; -32,768 to 32,767; 16 bits long myVar; 32 bits; -2,147,483,648 to 2,147,483,647; 32 bits long long myVar; 64 bits; -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807; 64 bits int myVar; 32 bits; -2,147,483,648 to 2,147,483,647; 16 bits int is the most commonly used integer type. long long is used for integers expected to exceed about 2 billion. That is not a typo; the word appears twice. In case the reader is wondering, the language does not have a simple way to print numbers with commas. So if x is 8000000, printing 8,000,000 is not trivial. A common error made by a program's user is to input the wrong type, such as inputting a string like twenty (rather than 20) when the input statement was cin >> myInt; where myInt is an int, which can cause strange program behavior. short is rarely used. One situation is to save memory when storing many (e.g., tens of thousands) of smaller numbers, which might occur for arrays (another section). Another situation is in embedded computing systems having a tiny processor with little memory, as in a hearing aid or TV remote control. Similarly, char, while technically a number, is rarely used to directly store a number, except as noted for short. Floating-point numeric data types. Definition Size Supported number range float x; 32 bits -3.4x1038 to 3.4*1038 double x; 64 bits -1.7x10308 to 1.7*10308 The compiler uses one bit for sign, some bits for the mantissa, and some for the exponent. Details are beyond our scope. The language (unfortunately) does not actually define the number of bits for float and double types, but the above sizes are very common. float is typically only used in memory-saving situations, as discussed above for short. Due to the fixed sizes of the internal representations, the mantissa (e.g, the 6.02 in 6.02e23) is limited to about 7 significant digits for float and about 16 significant digits for double. So for a variable defined as double pi, the assignment pi = 3.14159265 is OK, but pi = 3.14159265358979323846 will be truncated. On some processors, especially low-cost processors intended for "embedded" computing, like systems in an automobile or medical device, floating-point calculations may run slower than integer calculations, such as 100 times slower. Floating-point types are typically only used when really necessary. On more powerful processors like those in desktops, servers, smartphones, etc., special floating-point hardware nearly or entirely eliminates the speed difference. Floating-point numbers are sometimes used when an integer exceeds the range of the largest integer type.

Function

A function is a list of statements that can be executed by referring to the function's name.

character literal

A character literal is surrounded with single quotes, as in 'm' or '%'.

static_cast<type>

A common error is to accidentally perform integer division when floating-point division was intended. A programmer can precede an expression with static_cast<type>(expression) to convert the expression's value to the indicated type. For example, if myIntVar is 7, then static_cast<double>(myIntVar) converts int 7 to double 7.0. Such explicit conversion by the programmer of one type to another is known as type casting. Figure 2.11.2: Using type casting to obtain floating-point division: #include <iostream> using namespace std; int main() { int kidsInFamily1 = 3; // Should be int, not double int kidsInFamily2 = 4; // (know anyone with 2.3 kids?) int numFamilies = 2; // Should be int, not double double avgKidsPerFamily = 0.0; // Expect fraction, so double avgKidsPerFamily = static_cast<double>(kidsInFamily1 + kidsInFamily2) / static_cast<double>(numFamilies); cout << "Average kids per family: " << avgKidsPerFamily << endl; return 0; } A common error is to cast the entire result of integer division, rather than the operands, thus not obtaining the desired floating-point division. For example, static_cast<double>((5 + 10) / 2) yields 7.0 (integer division yields 7, then converted to 7.0) rather than 7.5.

constant variable (const)

A good practice is to minimize the use of literal numbers in code. One reason is to improve code readability. newPrice = origPrice - 5 is less clear than newPrice = origPrice - priceDiscount. When a variable represents a literal, the variable's value should not be changed in the code. If the programmer precedes the variable definition with the keyword const, then the compiler will report an error if a later statement tries to change that variable's value. An initialized variable whose value cannot change is called a constant variable. A common convention, or good practice, is to name constant variables using upper case letters with words separated by underscores, to make constant variables clearly visible in code.

type conversion

A type conversion is a conversion of one data type to another, such as an int to a double. The compiler automatically performs several common conversions between int and double types, such automatic conversion known as implicit conversion. For an arithmetic operator like + or *, if either operand is a double, the other is automatically converted to double, and then a floating-point operation is performed. For assignment =, the right side type is converted to the left side type. int-to-double conversion is straightforward: 25 becomes 25.0. double-to-int conversion just drops the fraction: 4.9 becomes 4. Consider the statement expectedMales = 0.504 * numBirths, where both variables are int type. if numBirths is 316, the compiler sees "double * int" so automatically converts 316 to 316.0, then computes 0.504 * 316.0 yielding 159.264. The compiler then sees "int = double" so automatically converts 159.264 to 159, and then assigns 159 to expectedMales.

char

A variable of char type can store a single character, like the letter m or the symbol %. A char is stored as a number, but thought of as a character. Though stored as a number, the compiler knows to output a char type as the corresponding character.

ASCII

ASCII is an early standard for encoding characters as numbers. The following table shows the ASCII encoding as a decimal number (Dec) for common printable characters (for readers who have studied binary numbers, the table shows the binary encoding also). Other characters such as control characters (e.g., a "line feed" character) or extended characters (e.g., the letter "n" with a tilde above it as used in Spanish) are not shown. Binary Dec Char 010 0000 32 space 010 0001 33 ! 010 0010 34 " 010 0011 35 # 010 0100 36 $ 010 0101 37 % 010 0110 38 & 010 0111 39 ' 010 1000 40 ( 010 1001 41 ) 010 1010 42 * 010 1011 43 + 010 1100 44 , 010 1101 45 - 010 1110 46 . 010 1111 47 / 011 0000 48 0 011 0001 49 1 011 0010 50 2 011 0011 51 3 011 0100 52 4 011 0101 53 5 011 0110 54 6 011 0111 55 7 011 1000 56 8 011 1001 57 9 011 1010 58 : 011 1011 59 ; 011 1100 60 < 011 1101 61 = 011 1110 62 > 011 1111 63 ? 100 0000 64 @ 100 0001 65 A 100 0010 66 B 100 0011 67 C 100 0100 68 D 100 0101 69 E 100 0110 70 F 100 0111 71 G 100 1000 72 H 100 1001 73 I 100 1010 74 J 100 1011 75 K 100 1100 76 L 100 1101 77 M 100 1110 78 N 100 1111 79 O 101 0000 80 P 101 0001 81 Q 101 0010 82 R 101 0011 83 S 101 0100 84 T 101 0101 85 U 101 0110 86 V 101 0111 87 W 101 1000 88 X 101 1001 89 Y 101 1010 90 Z 101 1011 91 [ 101 1100 92 \ 101 1101 93 ] 101 1110 94 ^ 101 1111 95 _ 110 0000 96 ` 110 0001 97 a 110 0010 98 b 110 0011 99 c 110 0100 100 d 110 0101 101 e 110 0110 102 f 110 0111 103 g 110 1000 104 h 110 1001 105 i 110 1010 106 j 110 1011 107 k 110 1100 108 l 110 1101 109 m 110 1110 110 n 110 1111 111 o 111 0000 112 p 111 0001 113 q 111 0010 114 r 111 0011 115 s 111 0100 116 t 111 0101 117 u 111 0110 118 v 111 0111 119 w 111 1000 120 x 111 1001 121 y 111 1010 122 z 111 1011 123 { 111 1100 124 | 111 1101 125 } 111 1110 126 ~

argument

An input value to a function appears between parentheses and is known as an argument, such as areaSquare below. double sideSquare = 0.0; double areaSquare = 49.0; sideSquare = sqrt(areaSquare); The function executes and returns a new value. In the example above, sqrt(areaSquare) returns 7.0, which is assigned to sideSquare. Invoking a function is a function call. Some function have multiple arguments. For example, pow(b, e) returns the value of be.

overflow

An integer variable cannot store a number larger than the maximum supported by the variable's data type. An overflow occurs when the value being assigned to a variable is greater than the maximum value the variable can store. A common error is to try to store a value greater than about 2 billion into an int variable. For example, the decimal number 4,294,967,297 requires 33 bits in binary, namely 100000000000000000000000000000001 (we chose the decimal number for easy binary viewing). Trying to assign that number into an int results in overflow. The 33rd bit is lost and only the lower 32 bits are stored, namely 00000000000000000000000000000001, which is decimal number 1.

Binary number (Base 2)

Because each memory location is composed of bits (0s and 1s), a processor stores a number using base 2, known as a binary number. For a number in the more familiar base 10, known as a decimal number, each digit must be 0-9 and each digit's place is weighed by increasing powers of 10. So the decimal number 212 represents 2*102 + 1*101 + 2*100 = 2*100 + 1*10 + 2*1 = 200 + 10 + 2 = 212. In base 2, each digit must be 0-1 and each digit's place is weighed by increasing powers of 2. So the binary number 1101 represents 1*23 + 1*22 + 0*21 + 1*20 = 1*8 + 1*4 + 0*2 + 1*1 = 8 + 4 + 0 + 1 = 13 (in base 10). The compiler translates decimal numbers into binary numbers before storing the number into a memory location. The compiler would convert the decimal number 212 to the binary number 11010100, meaning 1*128 + 1*64 + 0*32 + 1*16 + 0*8 + 1*4 + 0*2 + 0*1 = 212, and then store that binary number in memory.

Decimal number (Base 10)

For a number in the more familiar base 10, known as a decimal number, each digit must be 0-9 and each digit's place is weighed by increasing powers of 10. So the decimal number 212 represents 2*102 + 1*101 + 2*100 = 2*100 + 1*10 + 2*1 = 200 + 10 + 2 = 212.

compiler warning

Most compilers detect when a statement assigns to a variable a literal constant so large as to cause overflow. The compiler may not report a syntax error (the syntax is correct), but may output a compiler warning message that indicates a potential problem. A GNU compiler outputs the message "warning: overflow in implicit constant conversion", and a Microsoft compiler outputs "warning: '=': truncation of constant value". Generally, good practice is for a programmer to not ignore compiler warnings. A common source of overflow involves intermediate calculations. Given int variables num1, num2, num3 each with values near 1 billion, (num1 + num2 + num3) / 3 will encounter overflow in the numerator, which will reach about 3 billion (max int is around 2 billion), even though the final result after dividing by 3 would have been only 1 billion. Dividing earlier can sometimes solve the problem, as in (num1 / 3) + (num2 / 3) + (num3 / 3), but programmers should pay careful attention to possible implicit type conversions.

Math library:

Some programs require math operations beyond basic operations like + and *, such as computing a square root or raising a number to a power. Thus, the language comes with a standard math library that has about 20 math operations available for floating-point values. Table 2.10.1: Some functions in the standard math library: Function Description pow Raise to power sqrt Square root exp Exponential function log Natural logarithm log10 Common logarithm ceil Round up value fabs Compute absolute value floor Round down value fmod Remainder of division abs Compute absolute value cos Cosine sin Sine tan Tangent acos Arc cosine asin Arc sine atan Arc tangent atan2 Arc tangent with two parameters cosh Hyperbolic cosine sinh Hyperbolic sine tanh Hyperbolic tangent frexp Get significand and exponent ldexp Generate number from significand and exponent modf Break into fractional and integral parts Using a math function from the math library: #include <iostream> #include <cmath> using namespace std; ... double sideSquare = 0.0; double areaSquare = 49.0; sideSquare = sqrt(areaSquare); *The c in the library name cmath indicates that the library comes from a library originally available in the C language. A few additional math functions for integer types are defined in another library called cstdlib, requiring: #include <cstdlib> for use. For example, abs() is the math function for computing the absolute value of an integer.

implicit conversion

The compiler automatically performs several common conversions between int and double types, such automatic conversion known as implicit conversion.

Troubleshooting

Troubleshooting is another word for debugging. Far from being an occasional nuisance, debugging is a core programmer task, like diagnosing is a core medical doctor task. Skill in carrying out a methodical debugging process can improve a programmer's productivity. Figure 2.17.1: A methodical debugging process. Predict a possible cause of the problem Conduct a test to validate that cause Repeat A common error among new programmers is to try to debug without a methodical process, instead staring at the program, or making random changes to see if the output is improved.


Conjuntos de estudio relacionados

Case study 2 - The Nervous System

View Set

AP Stat Unit 2 Progress Check: MCQ Part A

View Set