该程序来自一个经典的计算机问题--龟兔赛跑, 我以前曾经写过一个, 不太好,因为受到了别人的一些影响, 最近,偶然想起一种新的方法, 于是便重写了一下程序, 我自认为还可以吧,只是在我的电脑上运行时, 随机数产生的不太好, 效果也不是很理想.注释我就不写了, 空间太小,写起来不顺利. 另外说一句, 该程序的原题来自于<<C程序设计教程>>的第7章指针的练习7.17题.
----飞天小龙
#include <stdio.h> #include <stdlib.h> #include <time.h>
void pass (int * charge); void road (char * s, int * step, char count); void ouch (char * t, int a1, int a2); int wins (int count1, int count2);
main ()
{ char line [72]; int hare [11] = {0, 0, 0, 9, 9, -12, 1, 1, 1, -2, -2}; int tie [11] = {0, 3, 3, 3, 3, 3, -6, -6, 1, 1, 1}; int i, b, c1 = 1, c2 = 1;
printf ("BANG!!!!!\n" "AND THAY'RE OFF!!!!!\n");
while (! wins (c1, c2)) { srand (time (NULL));
for (b = 0; b <= 70; b ++) line [b] = ' '; line [71] ='\0';
i = 1 + rand () % 10;
c1 += hare [i]; c2 += tie [i];
road (line, &c1, 'H'); road (line, &c2, 'T');
ouch (line, c1, c2); sleep (1);
}
getch (); return 0;
}
void pass (int * charge)
{
if (*charge > 70) *charge = 70;
else if (*charge < 1) *charge = 1;
}
void road (char * s, int * step, char count)
{ pass (step); s [*step] = count; }
int wins (int count1, int count2)
{
if (count1 == 70) { printf ("Hare wins. YUCH.\n"); return 1; } else if (count2 == 70) { printf ("TORTOISE WINS!!! YAY!!!\n"); return 1; } else if (count1 == count1 && count2 == 70) { printf ("It's a tie.\n"); return 1; }
return 0;
}
void ouch (char * t, int a1, int a2)
{ if (a1 == a2 && a1 != 70) printf ("OUCH!!!!!\n\n"); else printf ("%s\n\n", t); }