设为首页 加入收藏

TOP

1.6.1 Game Stats 2.0程序简介
2013-10-07 14:41:15 来源: 作者: 【 】 浏览:46
Tags:1.6.1 Game Stats 2.0 程序 简介

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  使用不同方式更改每个变量

  1. // Game Stats 2.0  
  2. // Demonstrates arithmetic operations with variables  
  3. #include <iostream> 
  4. using namespace std;  
  5. int main()  
  6. {  
  7.          unsigned int score = 5000;  
  8.          cout << "score: " << score << endl;  
  9. //altering the value of a variable  
  10.          scorescore = score + 100;  
  11.          cout << "score: " << score << endl;  
  12.          //combined assignment operator  
  13.          score += 100;  
  14.          cout << "score: " << score << endl;  
  15.          //increment operators  
  16.          int lives = 3;  
  17.          ++lives;  
  18.          cout << "lives: "  << lives << endl;  
  19.          lives = 3;  
  20. lives++;  
  21.          cout << "lives: "  << lives << endl;  
  22.          lives = 3;   
  23.          int bonus = ++lives * 10;  
  24.          cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  25. lives = 3;   
  26.          bonus = lives++ * 10;  
  27.          cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  28.          //integer wrap arround  
  29.          score = 4294967295;  
  30.          cout << "\nscore: " << score << endl;  
  31.          ++score;  
  32.          cout << "score: "   << score << endl;  
  33.          return 0;  
  34. }  

陷阱

当编译该程序时,可能得到如"[Warning] this decimal constant is unsigned"这样的警告。幸运的是,警告不会阻止程序的编译和运行。该警告是整数溢出的结果。您也许希望在程序中避免整数溢出。然而,本程序有意使用了这种溢出并显示这种情况的结果。1.6.5节在讨论这段程序时,将介绍关于整数溢出的知识。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.5.2 基本类型 下一篇17.9.2 新建相册模块的设计与实现..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: