关于srand(time(0))的使用方法

Rosalia ·
更新时间:2024-09-20
· 944 次阅读

参考

关于rand()和srand()

问题

起因是想测试一下酒馆战棋十二胖头鱼大乱斗先后手的胜率,测试代码如下:

#include #include #include #define TIMES 1000000 #define PRINT 0 int win, draw, lose; int score, combat; int p1cur, p2cur; int p1rem, p2rem; int p1sta[6], p2sta[6]; int p1tab[6], p2tab[6]; void battle(bool first); void battle(int p1no, int p2no); bool wlcheck(); void printcur(); int main() { win = draw = lose = 0; score = combat = 0; int t = 0; srand(time(0)); while (t++ < TIMES) { //千万不要把srand(time(0))写在这里 p1cur = p2cur = 5; p1rem = p2rem = 6; for (int i = 0; i < 6; i++) { p1sta[i] = p2sta[i] = 1; p1tab[i] = p2tab[i] = i; } while (1) { battle(1); if (wlcheck())break; printcur(); battle(0); if (wlcheck())break; printcur(); } } printf("先手胜率:%f%%\n后手胜率:%f%%\n平局率:%f%%\n平均存活随从数:%f\n平均战斗次数:%f\n", (double)win * 100 / TIMES, (double)lose * 100 / TIMES, (double)draw * 100 / TIMES, (double)score / TIMES, (double)combat / TIMES); } void battle(bool first) { if (first) { do { if (p1cur == 5)p1cur = 0; else p1cur++; } while (p1sta[p1cur] == -1); battle(p1cur, p2tab[rand() % p2rem]); } else { do { if (p2cur == 5)p2cur = 0; else p2cur++; } while (p2sta[p2cur] == -1); battle(p1tab[rand() % p1rem], p2cur); } } void battle(int p1no, int p2no) { combat++; if (--p1sta[p1no] == -1) { p1rem--; int i = -1; while (p1tab[++i] != p1no); while (i < p1rem) p1tab[i++] = p1tab[i + 1]; } if (--p2sta[p2no] == -1) { p2rem--; int i = -1; while (p2tab[++i] != p2no); while (i < p2rem) p2tab[i++] = p2tab[i + 1]; } for (int i = 0; i < 6; i++) { if (p1sta[i] == 0 && p1no != i)p1sta[i] = 1; if (p2sta[i] == 0 && p2no != i)p2sta[i] = 1; } } bool wlcheck() { if (p1rem == 0 && p2rem == 0) { draw++; return true; } else if (p1rem == 0) { lose++; score -= p2rem; return true; } else if (p2rem == 0) { win++; score += p1rem; return true; } else return false; } void printcur() { if (!PRINT)return; for (int i = 0; i < 6; i++) printf("%d ", p1sta[i]); printf("\n"); for (int i = 0; i < 6; i++) printf("%d ", p2sta[i]); printf("\n\n"); } 结果

多次运行结果相差不大,后手胜率稍微领先一点点。
在这里插入图片描述

结论

使用srand(time(0))初始化随机数发生器时一定要写在循环之外,否则如果循环每次执行时间小于1s,则获得的随机数就是完全相同的一组。


作者:kybxdkybxd



srand time 方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章