我是 C++ 的初学者程序员。我在一本旧的 c++ 书中发现了一个非常有趣的练习,它没有该练习的解决方案,所以我希望你们能帮助我:
它要我创建一副 52 张牌,然后洗牌并将牌发给 4 位玩家:
这是代码示例:
cout << "Player 1: ";
for (int j=0; j<13; j++)
{
card[j].display();
cout << ", ";
}
玩家 1:8、7、3、2、A、K、5、4、Q、9、3、A、2
现在它要我从大到小排列这些数字:A, A, K, Q, 9 ,8, 7,5 ,4, 3, 3,2, 2
在互联网上进行了研究之后,我学会了如何找到数组的最大数字,但我仍然不知道如何将这些数字从最大到最小排列。我正在使用 GNU 编译器。
谢谢。
对于那些想要所有代码的人,这里是:
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
enum Suit {clubs, diamonds, hearts, spades};
class deck
{
private:
int number;
Suit suit;
public:
void setcards(int n, Suit s)
{ number = n; suit = s; }
void display();
};
void deck::display()
{
if (number >= 2 && number <= 10)
cout << number;
else
switch(number)
{
case 11: cout << "J"; break;
case 12: cout << "Q"; break;
case 13: cout << "K"; break;
case 14: cout << "A"; break;
}
switch(suit)
{
case clubs: cout << static_cast <char> (5); break;
case diamonds: cout << static_cast <char> (4); break;
case hearts: cout << static_cast <char> (3); break;
case spades: cout << static_cast <char> (6); break;
}
}
class game
{
private:
int j;
enum {cardmax = 52};
deck card[cardmax];
public:
game()
{
for (int j=0; j<cardmax; j++)
{
int num = (j % 13) + 2;
Suit su = Suit(j / 13);
card[j].setcards(num, su);
}
}
void shuffle()
{
char ans;
cout << "Would you like to shuffle the deck? (y/n): ";
cin >> ans;
if (ans == 'y')
{
srand(time(NULL));
for (j=0; j<cardmax; j++)
{
int k = rand() % 52;
deck temp = card[j];
card[j] = card[k];
card[k] = temp;
}
}
else if (ans =='n')
deal();
}
void deal();
};
void game::deal()
{
const char esc = 27;
const char enter = '\r';
char ans;
cout << "Press ESCAPE to exit the game or ENTER to deal: ";
ans = getche();
if (ans == esc)
exit(0);
else if (ans == enter)
{
cout << "\n\nPlayer 1: ";
for (j=0; j<13; j++)
{
card[j].display();
cout << ", ";
}
cout << "\nPlayer 2: ";
for (j=13; j<26; j++)
{
card[j].display();
cout << ", ";
}
cout << "\nPlayer 3: ";
for (j=26; j<39; j++)
{
card[j].display();
cout << ", ";
}
cout << "\nPlayer 4: ";
for (j=39; j<52; j++)
{
card[j].display();
cout << ", ";
}
cout << endl;
cout << "\nWould you like to deal again? (y/n): ";
cin >> ans;
if (ans == 'y')
{
shuffle();
deal();
}
else if (ans == 'n')
exit(0);
}
}
int main()
{
game cards;
cards.shuffle();
cards.deal();
}