1.6 使用变量进行算术运算
一旦有了存储值的变量,我们就希望在游戏的过程中改变它们的值:也许希望通过对击败Boss的玩家加分给予奖励,或许又希望降低气阀里的氧气含量。之前介绍的(和一些新的)运算符可以完成这些任务。
1.6.1 Game Stats 2.0程序简介
Game Stats 2.0程序对表示游戏统计值的变量进行操作并显示结果。程序运行结果如图1-6所示。
从Course Technology网站(www.courseptr.com/downloads)或本书合作网站(http://www. tupwk.com.cn/downpage)上可以下载到该程序的代码。程序位于Chapter 1文件夹中,文件名为game_stats2.cpp。
|
| 图1-6 使用不同方式更改每个变量 |
- // Game Stats 2.0
- // Demonstrates arithmetic operations with variables
- #include <iostream>
- using namespace std;
- int main()
- {
- unsigned int score = 5000;
- cout << "score: " << score << endl;
- //altering the value of a variable
- scorescore = score + 100;
- cout << "score: " << score << endl;
- //combined assignment operator
- score += 100;
- cout << "score: " << score << endl;
- //increment operators
- int lives = 3;
- ++lives;
- cout << "lives: " << lives << endl;
- lives = 3;
- lives++;
- cout << "lives: " << lives << endl;
- lives = 3;
- int bonus = ++lives * 10;
- cout << "lives, bonus = " << lives << ", " << bonus << endl;
- lives = 3;
- bonus = lives++ * 10;
- cout << "lives, bonus = " << lives << ", " << bonus << endl;
- //integer wrap arround
- score = 4294967295;
- cout << "\nscore: " << score << endl;
- ++score;
- cout << "score: " << score << endl;
- return 0;
- }
陷阱
当编译该程序时,可能得到如"[Warning] this decimal constant is unsigned"这样的警告。幸运的是,警告不会阻止程序的编译和运行。该警告是整数溢出的结果。您也许希望在程序中避免整数溢出。然而,本程序有意使用了这种溢出并显示这种情况的结果。1.6.5节在讨论这段程序时,将介绍关于整数溢出的知识。