《编程之美随书源代码_中文注释》由会员分享,可在线阅读,更多相关《编程之美随书源代码_中文注释(64页珍藏版)》请在金锄头文库上搜索。
1、. . . .第1章游戏之乐游戏中碰到的题目代码清单1-11.int main() for(; ; for(int i = 0; i 9600000; i+) ; Sleep(10); return 0;代码清单1-2int busyTime = 10; / 10 ms int idleTime = busyTime; / same ratio will lead to 50% cpu usageInt64 startTime = 0;while(true) startTime = GetTickCount(); / busy loop while(GetTickCount() - start
2、Time) level) System.Threading.Thread.Sleep(10); 代码清单1-4/ C+ code to make task manager generate sine graph#include Windows.h#include stdlib.h#include math.hconst double SPLIT = 0.01;const int COUNT = 200;const double PI = 3.14159265;const int INTERVAL = 300;int _tmain(int argc, _TCHAR* argv) DWORD bu
3、sySpanCOUNT;/ array of busy times DWORD idleSpanCOUNT;/ array of idle times int half = INTERVAL / 2; double radian = 0.0; for(int i = 0; i COUNT; i+) busySpani = (DWORD)(half + (sin(PI * radian) * half); idleSpani = INTERVAL - busySpani; radian += SPLIT; DWORD startTime = 0; int j = 0; while(true) j
4、 = j % COUNT; startTime = GetTickCount(); while(GetTickCount() - startTime) = busySpanj) ; Sleep(idleSpanj); j+; return 0;代码清单1-5_PROCESSOR_POWER_INFORMATION info;CallNTPowerInformation(11, / query processor power information NULL, / no input buffer 0, / input buffer size is zero &info, / output buf
5、fer Sizeof(info); / outbuf size _int64 t_begin = GetCPUTickCount(); / do something _int64 t_end = GetCPUTickCount(); double millisec = (double)t_end (double)t_begin) /(double)info.CurrentMhz;代码清单1-6#define HALF_BITS_LENGTH 4/ 这个值是记忆存储单元长度的一半,在这道题里是4bit#define FULLMASK 255/ 这个数字表示一个全部bit的mask,在二进制表示中
6、,它是11111111。#define LMASK (FULLMASK HALF_BITS_LENGTH)/ 这个数字表示右bits的mask,在二进制表示中,它表示00001111。#define RSET(b, n) (b = (LMASK & b) n)/ 这个宏,将b的右边设置成n#define LSET(b, n) (b = (RMASK & b) (n HALF_BITS_LENGTH)/ 这个宏得到b的左边的值#define GRIDW 3/ 这个数字表示将帅移动范围的行宽度。#include #define HALF_BITS_LENGTH 4#define FULLMASK
7、255#define LMASK (FULLMASK HALF_BITS_LENGTH)#define RSET(b, n) (b = (LMASK & b) n)#define LSET(b, n) (b = (RMASK & b) (n HALF_BITS_LENGTH)#define GRIDW 3int main() unsigned char b; for(LSET(b, 1); LGET(b) = GRIDW * GRIDW; LSET(b, (LGET(b) + 1) for(RSET(b, 1); RGET(b) = GRIDW * GRIDW; RSET(b, (RGET(b
8、) + 1) if(LGET(b) % GRIDW != RGET(b) % GRIDW) printf(A = %d, B = %dn, LGET(b), RGET(b); return 0;代码清单1-7struct unsigned char a:4; unsigned char b:4; i;for(i.a = 1; i.a = 9; i.a+) for(i.b = 1; i.b = 9; i.b+) if(i.a % 3 != i.b % 3) printf(“A = %d, B = %dn”, i.a, i.b);代码清单1-8/*/ 烙饼排序实现/*/class CPrefixS
9、ortingpublic: CPrefixSorting() m_nCakeCnt = 0; m_nMaxSwap = 0; CPrefixSorting() if( m_CakeArray != NULL ) delete m_CakeArray; if( m_SwapArray != NULL ) delete m_SwapArray; if( m_ReverseCakeArray != NULL ) delete m_ReverseCakeArray; if( m_ReverseCakeArraySwap != NULL ) delete m_ReverseCakeArraySwap; / / 计算烙饼翻转信息 / param / pCakeArray存储烙饼索引数组 / nCakeCnt烙饼个数 / void Run(int* pCakeArray, int nCakeCnt) Init(pCakeArray, nCakeCnt); m_nSearch = 0; Search(0);