正文

用C++模拟龟兔赛跑2009-07-31 20:36:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/shao/45924.html

分享到:

// Chapter 5 of C++ How to Program// tortoiseandhare.cpp#include <iostream> using std::cout;using std::endl; #include <cstdlib> #include <ctime> #include <iomanip> using std::setw; const int RACE_END = 70; /* Write prototype for moveTortoise here */void moveTortoise(int &);/* Write prototype for moveHare here */void moveHare(int &);/* Write prototype for printCurrentPositions here */void printCurrentPositions(int &,int &); int main(){   int tortoise = 1, hare = 1, timer = 0;      srand( time( 0 ) );   cout<<"A program to show the match between the tortoise and the hare!"<<endl<<endl;    cout << "ON YOUR MARK, GET SET\nBANG               !!!!"    <<endl        << "\nAND THEY’RE OFF    !!!!\n\n";      while ( tortoise != RACE_END && hare != RACE_END ) {      /* Write call for moveTortoise here */    moveTortoise(tortoise);      /* Write call for moveHare here */    moveHare(hare);      /* Write call for printCurrentPositions here */     printCurrentPositions(tortoise,hare);      ++timer;   }    if ( tortoise >= hare )      cout << "\nTORTOISE WINS!!! YAY!!!\n";   else      cout << "Hare wins. Yuch.\n";    cout << "TIME ELAPSED = " << timer << " seconds" << endl;   return 0;} /* Write function definition for moveTortoise here */void moveTortoise(int & turtlePtr){   int x = 1 + rand() % 10;    if ( x >= 1 && x <= 5 )        // fast plod      turtlePtr += 3;   else if ( x == 6 || x == 7 )   // slip      turtlePtr -= 6;   else                           // slow plod`      ++( turtlePtr );      if ( turtlePtr < 1 )      turtlePtr = 1;   else if ( turtlePtr > RACE_END )      turtlePtr = RACE_END;} /* Write function definition for moveHare here */void moveHare(int &rabbitPtr){   int y = 1 + rand() % 10;    /* Write statements that move rabbit */   if( y>= 1 &&y<=2)    rabbitPtr=rabbitPtr;   else if(y>=3&&y<=4)    rabbitPtr+=9;   else if(y==5)    rabbitPtr-=12;   else if(y>=6&&y<=8)    rabbitPtr+=1;   else    rabbitPtr-=2;    if(rabbitPtr<1)    rabbitPtr=1;   else if(rabbitPtr> RACE_END)    rabbitPtr= RACE_END;    /* Write statements that test if rabbit is before      the starting point or has finished the race */} /* Write function definition for printCurrentPositions here */void printCurrentPositions(int &bunnyPtr,int &snapperPtr){   if ( bunnyPtr == snapperPtr )       cout << setw( bunnyPtr ) << "OUCH!!!";         else if ( bunnyPtr < snapperPtr )       cout << setw( bunnyPtr ) << "H"            << setw( snapperPtr - bunnyPtr ) << "T";   else      cout << setw( snapperPtr ) << "T"            << setw( bunnyPtr - snapperPtr ) << "H";    cout << "\n";}

阅读(5845) | 评论(1)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册