// 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 score = 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 around score = 4294967295; cout << "\nscore: " << score << endl; ++score; cout << "score: " << score << endl; return 0; }
警告:整数溢出!
score=score+100;
语句的意思是:把score的当前值加上100,然后把结果赋给score。其效果是score的值增加了100。
score+=100;
“+=”组合赋值运算符:将右边的全部与左边的全部相加,然后将结果赋给左边。
放在变量之前,称为前置递增运算符;
放在变量之后,称为后置递增运算符;
前置递增运算符会在较大的表达式使用变量之前增加变量的值。
后置递增运算符会在较大的表达式使用变量之后增加变量的值。
溢出的结果:“溢出”到类型能表示的最小值。类似汽车的里程表。
反之,递减超出最小值,会溢出到最大值。
常量是经过命名的无法修改的值。
如果程序中频繁的使用到不变化的值,常量就很有用。
例如,每个在空中击毁的外星人都值150分,那么就可以定义一个名为ALIEN_POINTS的常量,其值为150.
// Game Stats 3.0 // Demonstrates constants #include <iostream> using namespace std; int main() { const int ALIEN_POINTS = 150; int aliensKilled = 10; int score = aliensKilled * ALIEN_POINTS; cout << "score: " << score << endl; enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE}; difficulty myDifficulty = EASY; enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50}; shipCost myShipCost = BOMBER_COST; cout << "\nTo upgrade my ship to a Cruiser will cost " << (CRUISER_COST - myShipCost) << " Resource Points.\n"; return 0; }
表示外星人的分值。
枚举类型是unsigned int型常量的集合,其中的常量称为枚举数。
通常情况下枚举数是相关的,并且有特定顺序。
enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};
默认情况下,枚举数的值从0开始,每次加1;
所以NOVICE=0,EASY=1.....
格式:关键词enum+标识符+{枚举数......};
定义枚举类型的变量:
difficulty myDifficulty = EASY;
注意:只能用NOVICE, EASY, NORMAL, HARD, UNBEATABLE,0,1,2,3,4对myDifficulty赋值。
enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};
shipCost这一枚举类型,用来表示在策略游戏中建造这些飞船花费的资源点。某些枚举数被赋予了特定的整数值。这些值表示每种船只的资源点。
注意:没有被赋值的枚举数的取值为前一个枚举数的值加1;
即,BOMBER_COST被初始化为26.
可以对枚举数进行算术运算。
原文:https://www.cnblogs.com/wlyperfect/p/12368382.html