我现在在编一个程序,大意是 :有52张牌,电脑随机抽13张,显示13张牌!!
但是我不知道,该用什么函数啊??
以前都是自定义输入的,碰到随机的还真不知道该怎么搞!!
#include <iostream> #include <string> #include <cstdlib> #include <ctime> #include <windows.h> using namespace std;
#define set_color(i, c) c = (i==0)?"hei":((i==1)?"hong":((i==2)?"cao":((i==3)?"fang":""))) struct Card { char value; string color; };
class Cards { private: Card * myCards; int total; public: Cards(); Cards(int n); void get_13_cards(Cards * my_13_cards); void display(); ~Cards() { if(myCards && total == 1) { total = 0; delete myCards; } else { total = 0; delete []myCards; } } };
Cards::Cards() { myCards = NULL; total = 0; } Cards::Cards(int n) { int i = 0; int j = 0; if(n == 52) { myCards = new Card[52]; total = 52; for(i = 0; i<13; i++) { for(j = 0; j<4; j++) { myCards[4*i+j].value = i+1; set_color(j, myCards[4*i+j].color); } } } else { myCards = new Card[n]; total = n; for(i = 0; i<n; i++) { myCards[i].value = 0; myCards[i].color = " "; } } } void Cards::get_13_cards(Cards * my_13_cards) { int count = 0; int pos = 0; srand( (unsigned)GetTickCount() );
do { pos = rand()%52; if(myCards[pos].value) { ((my_13_cards->myCards)+count)->value = myCards[pos].value; ((my_13_cards->myCards)+count)->color = myCards[pos].color; myCards[pos].value = 0; myCards[pos].color = " "; count++; } }while(count<13);
} void Cards::display() { for(int i = 0; i<total; i++) { if((myCards+i)->value==11) cout<<i+1<<".Card: "<<'J'<<" "<<(myCards+i)->color<<endl; else if((myCards+i)->value==12) cout<<i+1<<".Card: "<<'Q'<<" "<<(myCards+i)->color<<endl; else if((myCards+i)->value==13) cout<<i+1<<".Card: "<<'K'<<" "<<(myCards+i)->color<<endl; else cout<<i+1<<".Card: "<<(int)((myCards+i)->value)<<" "<<(myCards+i)->color<<endl; } }
int main() { Cards myCards(52); Cards my_13_Cards(13); myCards.get_13_cards(&my_13_Cards); my_13_Cards.display();
system("pause"); return 0; }