1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ Programming for Games Module I phần 2 potx

24 357 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 24
Dung lượng 3,28 MB

Nội dung

Pro mgra 1.6: Type Conversions. // Demonstrates some type conversions. #include <iostream> using namespace std; int main() { ert from a less precise type // Case 1: Conv // to a more precise type: char c = 10; short s = c; cout << “char to short: “ << s << endl; // Case 2: Convert from a more precise integer // to a less precise integer: unsigned char uc = 256; cout << “int to uchar: “ << (int)uc << endl; // Case 3: Convert from a float to an int, // assuming the int can store the float’s value. int i = 496512.546f; cout << “float to int: “ << i << endl; // Case 4: Convert from a float to a short, this // time the int can’t store the float: s = 496512.987123f; cout << “float to short: “ << s << endl; } P Output. rogram 1.6: char to short: 10 int to uchar: 0 float to int: 496512 float to short: -27776 Press any key to continue • Case 1: Here we convert from a less precise type to a more precise type. Since the more precise type can fully represent the less precise type, there is no conversion problem and everything works out as expected. 28 • Case 2: Here we convert from a more precise integer to a less precise integer. However, an unsigned char cannot represent the value 256. What happens is called wrapping. The unsigned char cannot store values over 255 so it wraps back to zero. Thus 256 becomes • an int. Observe that the float is truncated—the float • a short, but the short cannot store the whole number part ping scenario. a serious problem that can lead to hard-to-find bugs. Thus, you should orking with values that your types can correctly store. es these type conversions implicitly; that is, automatically. However, sometimes ou nee ll the compiler to treat a type as a different type. We actually see this in Case 2 of Program “ << (int)uc << endl; The (int)uc syntax tells the compiler to treat uc as an int, not as a char. This is because cout will e general, this type of casting can be done with either of the llowing syntaxes: result = static_cast<typeToConvertTo>(valueToConvert); vert; int y = (int)result; zero, 257 would become 1, 258 would become 2, and so on. The values “wrap” back around. Wrapping also occurs in the opposite direction. For instance, if we assigned –1 to an unsigned char , the value would wrap around in the other direction and become 255. Case 3: Here we assign a float to loses its decimal. Case 4: Here we assign a float to of the float. Thus we observe a wrap Note: Integer wrapping is always ensure that you are w he C++ compiler doT y d to explicitly te 1.6. Specifically, the line: cout << “int to uchar: output the character representation of uc since it is a char. But we want it to output the integer representation of the char. Thus we must perform a type cast (conversion between types) and xplicitly tell the compiler to treat uc as an int. In fo result = (typeToConvertTo) valueToCon Examples: int x = 5; float result = static_cast<float>(x); 29 .3.7 Typedefs 1 At some point, you might find a C++ type that is too long. For example, unsigned int is a lot to allows you to define an alternate name (synonym) via the typedef keyword. ine the following shorter names for the unsigned types: f unsigned long ulong; f having to write: 19; e can simply write: Variables es we will want to define a variable that cannot change. Such variables are constant. For , we may want to define a constant variable pi to represent the mathematical constant write out repeatedly. C++ For example, we might def typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typede Thus, for example, instead o unsigned int x = W uint x = 19; 1.3.8 Const Sometim example 14.3 ≈ π . ifying keyword: // error, cannot redefine constant pi. notational convenience. It is clearer to read the symbolic name a programmer may not immediately connect 3.14 to To do this we use the const mod const float pi = 3.14f; If the programmer tries to change pi, an error will result: pi = 12.53f; Constant variables are often used for π “pi” than it is to read the number 3.14; . 1.3.9 Macros Sometimes we want to create a symbol name (identifier) that stands for some set of code. We can do this by defining a macro. For example, the following line of code defines a macro PRINTHELLO, which hen written, executes the statement: cout << "Hello" << endl;. // Define a macro PRINTHELLO that means < endl; w // "cout << 'Hello' << endl;" #define PRINTHELLO cout << "Hello" < 30 Using this macro we could write a program that outputs “Hello” several times like so: Program 1.7: Macros #include <iostream> using namespace std; // Define a macro PRINTHELLO that means // "cout << 'Hello' << endl;" #define PRINTHELLO cout << "Hello" << endl; int main() { PRINTHELLO PRINTHELLO PRINTHELLO PRINTHELLO } Note that the semi-colon is inc ition a to place one at the end of each line. Program 1.7 Output luded in the macro defin nd thus we did not need Hello Hello Hello Hello Press any key to continue When the compiler compiles the source code and encounters a macro, it internally replaces the macro mbol with the code for which it stands. Program 1.7 is expanded internally as: endl; "Hello" << endl; "Hello" << endl; thmetic Operations sy int main() { cout << "Hello" << cout << "Hello" << endl; cout << cout << } 1.4 Ari 31 In addition to declaring, defining, inputting, and outputting variables of various types, we can perform them. Unary Operator Description Example basic arithmetic operations between 1.4.1 Unary Arithmetic Operations A unary operation is an operation that acts on one variable (operand). Table 1.2 summarizes three unary operators: Table 1.2: Unary Operations. Negation Operator: - Negates the operand. int x = 5; int y = -x; // y = -5. Increment Operator: ++ Increments the operand by e increment operator can prefix or postfix the operator. int x = 5; ++x; // x = 6 (prefix) x++; // x = 7 (postfix) one. Note that th Decrement Operator: Decrements the operand by one. Note that the decrement operator can prefix or postfix the int x = 5; x; // x = 4 (prefix) x ; // x = 3 (postfix) operator. Observe that the increment and decrement operators can be written as a prefix or postfix. The technical ifference between prefix and postfix is determined by where the increment/decrement occurs in a illustrates: d statement. The following program rogram 1.8: Prefix versus Postfix. P #include <iostream> using namespace std; int main() { int k = 7; cout << "++k = " << ++k << endl; cout << "k++ = " << k++ << endl; cout << k << endl; } 1.8: Output. Program ++k = 8 k++ = 8 32 9 Press any key to continue D see the difference betwo you een the prefix and postfix increment/decrement operator? In the first call cou layed. Hence the number 8 is displayed. owev <, k is first displayed, and then is incremented. Hence the mbe at it was indeed incremented, expression, when using the efix decremented first, before it is used. Conversely, when using the , after it is used. 4.2 Operations ++ co Multiplication operator (*), (/) (%). n, multiplication and division are defined for all numeric types. The modulus nteger operation only. The only arithmetic operation defined for std::string is the addition operator. The following program illustrates the arithmetic operations: to t <<, k is incremented first, before being disp er, in the second call to cout < H nu r 8 is displayed again. Finally, we output k a third time to show th cond time. Therefore, in a complexbut only after it was displayed the se form, the value is incremented/pr postfix form, the value is incremented/decremented last 1. Binary Arithmetic C ntains five binary arithmetic operators: 1) Addition operator (+), Subtraction operator (-), 2) )3 4) Division operator 5) Modulus operator Addition, subtractio operator is an i Program 1.9: Arithmetic Operations. // Program demonstrates some arithmetic operations. #include <iostream> #include <string> using namespace std; int main() { //========================= // Do some math operations: float f1 = 10.0f * 10.0f; float f2 = f / 10.0f; 1 float fDif = f1 - f2; cout << f1 << " - " << f2 << " = " << fDif; cout << endl << endl; 33 //============================ // Do some integer operations: int i1 = 19 + 4; int i2 = 10 - 3; int remainder = i1 % i2; cout << i1 << " % " << i2 << " = " << remainder; cout << endl << endl; //=========================== // Do some string operations: string s1 = "Hello, "; string s2 = "World!"; string stringSum = s1 + s2; cout << s1 << " + " << s2 << " = " << stringSum; cout << endl << endl; } Program 1.9: Output. 100 - 10 = 90 23 % 7 = 2 Hello, + World! = Hello, World! Press continue any key to 1.4.3 e modulus operator returns the remainder of an integer division. For example, The Modulus Operator Th 7 3 7 += . 223 H e call the nere w umerator 2, in 72 , the remainder—it is the remaining part that cannot be divided enly We will say two integers divide evenly if and only if the division results in an integer; ., no ple, ev by seven. ( i.e t a fraction.) Consider the exam 135 . In this case, the remainder is five; that is, 13 divides into 5 zero times, and the r rt that cannot be evenly divided by 13 is 5. so emaining pa 34 1. Compound Arithmetic Oper4.4 ations + de lly perform two operations, namely an arithmetic eration and an assignment operation. The following table summarizes: ithmetic Operations. tion Equivalent Meaning C+ p fines the following “shortcut” operators that rea o Table 1.3: Compound Ar Compound Arithmetic Opera x += y x = x + y x -= y x = x – y x *= y x = x * y x /= y x = x / y x %= y x = x % y The following program illustrates how they are used in a C++ program: Program 1.10: Compound Arithmetic Operators. #include <iostream> using namespace std; int main() { int x = 0; int y = 0; cout << "Enter an integer: "; cin >> x; cout << "Enter an integer: "; cin >> y; // Save to separate variables so each operation is // independent of each other. int a = x; int b = x; int c = x; int d = x; int e = x; a += y; b -= y; c *= y; d /= y; e %= y; cout << "x += y = " << a << endl; 35 out << "x -= y = " << b << endl; c cout << "x *= y = " << c << endl; cout << "x /= y = " << d << endl; cout << "x %= y = " << e << endl; } Program 1.10: Output. Enter an integer: 50 Enter an integer: 12 x += y = 62 x -= y = 38 x *= y = 600 x /= y = 4 x %= y = 2 Press any key to continue Note: The output of Program 1.9 brings up an important point. Namely, 50 / 12 is not 4, but approximately 4.1667. What happened? The decimal portion of the answer is lost because integers are being used, and they are unable to represent decimals. Bear this truncation in mind when doing division with integers and ask yourself whether or not this is a problem for your particular circumstances. Con in n w prece e r of greatest precedence to least precedence. ultiplication, division and the modulus operations have the same precedence level. Similarly, addition and divi n division above e ot Someti e add cedence to an operation by rrounding it with a pair of parentheses, much like you do in mathematical notation. We can force the addition to come before multiplication by using the following parentheses: 1.4.5 Operator Precedence sider the following statement: t x = 5 + 3 * 8; I hich order will the compiler perform the various arithmetic operations? Each operator has a defined d nce level, and operators are evaluated in the orde M subtraction have the same precedence level. However, the precedence level of multiplication, sio , and modulation is greater than that of addition and subtraction. Therefore, multiplication, , and modulation operations always occur before addition and subtraction operations. Thus the xpression is evaluated like so: int x = 5 + 3 * 8; = 5 + 24 = 29 N e that operators with the same precedence level are evaluated left to right. mes you want to force an operation to occur first. For example, you may have actually wanted ition to take place before the multiplication. You can give greatest preth su 36 nt x = (5 + 3) * 8; i = 8 * 8 = 64 Par h should e inne ple illustrates: int x = (((5 + 3) - 2) * 6) + 5; ) * 6) + 5 + 5 = 36 + 5 = 41 ns evaluate to a numeric value. The terminology for something that evaluates to a number is called a numeric expression. More generally, something that evaluates xists lo C++ code to object code. The linker then combines the object code, produce an executable program that can be run on the operating age code). 2. White space consists of blank lines and spaces, which are ignored by the compiler. Use white ur code in a more readable way. 3. The C++ standard library includes code for outputting and inputting data to and from the console 4. Every C++ program must have a main function, which defines the program entry point. 5. Namespaces are used to organize code into logical groupings and to prevent name clashes. 6. A variable occupies a region of physical system memory and stores a value of some type. Variable names can consist of letters and numbers, but cannot begin with a number (the is considered a letter). Recall that C++ is case sensitive. ent eses can also be nested so that you can explicitly specify the second, third, etc. operation that occur. In an expression with nested parentheses, the operations are evaluated in the order from rmost parentheses to the outermost parentheses. The following examth = ((8 – 2 = (6 * 6) Note: Observe how arithmetic operatio to something else is considered an expression. As you will see in the next chapter, there e gical expressions (expressions with logical operators), which evaluate to truth-values. 1.5 Summary 1. A C++ compiler translates from several object files, to system (i.e., machine langu space to format yo window, functions for computing various math operations such as sine and cosine, random number generators, code for saving and loading files to and from the hard drive, code to work with strings, and much, much more. underscore 37 [...]...7 C++ can implicitly convert between its intrinsic types; however, one must be alert for decimal truncation and integer wrapping It is good practice to try and avoid type conversions when practical 8 The rules of operator precedence define the order in which the compiler performs a series of operations Use parentheses to explicitly define the order in which the operations should be performed Consequently,... first evaluating the logical operations yourself, either mentally or on paper It is important that you are able to evaluate logical expressions mentally and quickly, and some of the exercises of this chapter will help you in building this skill The “hardest” logical expression Program 2. 2 performs is the “complex” one Therefore, we will walk through the evaluation of this expression step-by-step for. .. Chapter 2 Logic, Conditionals, Loops and Arrays Introduction 41 The previous chapter covered the creation of trivial C++ programs, but we are still very limited in terms of the ideas we can express using C++ In this chapter we expand our C++ “vocabulary” and “grammar” in order to program more interesting actions such as, “If the player’s hitpoints are less than zero then the player is dead and the game is... coincidentally, this is the same result which Program 2. 2 calculated Finally, observe that like the arithmetic operators, we can use parentheses to control the order in which the logical operators are evaluated 2. 3 Conditional Statements: If, If…Else Now that we can form boolean expressions with both the relational and logical operators, we can begin to form conditional statements In general, a conditional... real number n2: -14 .2 + -14 .2 = 50.47 - -14 .2 = 78.87 * -14 .2 = -918.314 / -14 .2 = -4.55 423 any key to continue 1.6 .2 Cin/Cout Rewrite the program example given in Section 1.1.3 This time, ask the user to enter his first and last names, separated by a space, on one line (i. e., use one “cin >>” operation to read both the first and last name in one pass) Does a problem occur? If so, describe it in complete... . arithmetic operation defined for std::string is the addition operator. The following program illustrates the arithmetic operations: to t <<, k is incremented first, before being disp er,. will say two integers divide evenly if and only if the division results in an integer; ., no ple, ev by seven. ( i. e t a fraction.) Consider the exam 135 . In this case, the remainder is five;. ultiplication, division and the modulus operations have the same precedence level. Similarly, addition and divi n division above e ot Someti e add cedence to an operation by rrounding

Ngày đăng: 05/08/2014, 09:45

TỪ KHÓA LIÊN QUAN