当前位置: 代码迷 >> C语言 >> [转帖]飞天小龙的龟兔赛跑程序:我自有我的方法
  详细解决方案

[转帖]飞天小龙的龟兔赛跑程序:我自有我的方法

热度:253   发布时间:2005-03-18 12:49:00.0
[转帖]飞天小龙的龟兔赛跑程序:我自有我的方法

该程序来自一个经典的计算机问题--龟兔赛跑, 我以前曾经写过一个, 不太好,因为受到了别人的一些影响, 最近,偶然想起一种新的方法, 于是便重写了一下程序, 我自认为还可以吧,只是在我的电脑上运行时, 随机数产生的不太好, 效果也不是很理想.注释我就不写了, 空间太小,写起来不顺利. 另外说一句, 该程序的原题来自于<<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); }

搜索更多相关的解决方案: 飞天  小龙  龟兔赛跑  转帖  

----------------解决方案--------------------------------------------------------
  相关解决方案