需要C项目的帮助 [英] Need help with a C project
问题描述
我正在用C做一个大学项目的纸牌游戏。我基本上必须创建一个有2种卡类型的游戏,Card和CardDeck,写一个功能来洗牌,并在2个玩家之间发出8张牌。
我还需要能够允许用户输入他们想要使用的套牌数量,所以我认为我不能使用固定大小的数组,也许就像动态一样内存分配。
任何帮助都会非常感激。
我尝试了什么:
I'm doing a Card game in C for a university project. I basically have to create a game that has 2 card types,"Card" and "CardDeck", write a function to shuffle them and give out 8 cards between 2 players.
I also need to be able to allow the user to input the amount of decks they want to use, so I don't think I would be able to use a fixed size array, maybe like a dynamic memory allocation.
Any help would be much appreciated.
What I have tried:
#include <stdio.h>
//Data Type Card
enum suit
{
Club, Spade, Heart, Diamond
};
typedef enum suit Suit;
enum rank
{
Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace
};
typedef enum rank Rank;
struct card
{
Suit c_suit;
Rank c_rank;
};
typedef struct card Card;
void shuffle(Card * deck);
void shuffle(Card * deck)
{
int temp;
int y, x, t=0;
for (x = 52; x > 0 ; x--)
{
y = rand() % x;
temp = deck[x];
deck[x] = deck[y];
deck[y] = temp;
}
}
推荐答案
您已注册为新用户重新发布你的问题,或者你的一个同学已经试图让我们为他们做功课。
需要帮助C中的纸牌游戏。 [ ^ ]
无论答案是否相同。
You've either signed up as a new user to repost your question, or one of your classmates has already tried to get us to do their homework for them.
Need help with a card game in C.[^]
Regardless the answers will be the same.
您是否采用与会员12849609相同的课程?
一起工作!
需要帮助C中的纸牌游戏。 [ ^ ]
Are you taking the same course as Member 12849609?
Work together!
Need help with a card game in C.[^]
有两个问题:
There are two problems:
- 数组索引从C / C ++开始为零,但是你从52循环到1
- 使用
rand ()%x
可能无法给出预期的结果
- Array indexes start at zero with C/C++ but you are looping from 52 to 1
- Using
rand() % x
might not give the expected results
假设传递的 deck
数组的大小为52,你必须在0到51的范围内循环。
使用%
模数运算符 rand()
返回0到 x - 1 $ c范围内的随机值$ C>。因为
x
是你的循环变量,所以当x == 1时,可用范围将变小,直到结果变为1.
正确的实现可能是:
Assuming that the passed deck
array has a size of 52, you must loop within the range of 0 to 51.
Using the %
modulo operator with rand()
returns a random value in the range 0 to x - 1
. Because x
is your loop variable, the available range will get smaller until the result becomes 1 when x == 1.
A proper implementation might be:
void shuffle(Card * deck)
{
int temp;
int y, x;
for (x = 0; x < 52 ; x++)
{
y = rand() % 52;
temp = deck[x];
deck[x] = deck[y];
deck[y] = temp;
}
}
这篇关于需要C项目的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!