1

这里是 C 的新手。我正在尝试使用从数组中随机选择的字符串来初始化字符串。我遇到了障碍。这是我到目前为止所拥有的,可能有更好的方法来做到这一点。

我试图在每次运行时基本上显示一张随机牌(等级和花色,kC = 俱乐部之王)。

#include <stdio.h>
#include <time.h>
#include <string.h>

int main()

{
char rank[13] = {'a','2','3','4','5','6','7','8','9','t','j','q','k'};
char suit[4] = {'C','D','H','S'};
int first;
int second;

srand(time(NULL));

                first = rand()%rank;
                second = rand()%suit;

        printf("Your Card: %d %d", first, second);


return 0;

我怀疑rand不能像我尝试的那样随机化一个数组,但是有没有办法告诉rand从我的数组中进行选择?谢谢

4

3 回答 3

1
#include <stdio.h>
#include <time.h>
#include <string.h>

int main()
{
    char rank[13] = {'a','2','3','4','5','6','7','8','9','t','j','q','k'};
    char suit[4] = {'C','D','H','S'};
    int first;
    int second;

    srand(time(NULL));

    first = rand() % 13;
    second = rand() % 4;

    printf("Your Card: %c %c", rank[first], suit[second]);

    return 0;
}
于 2012-10-17T04:32:42.233 回答
0

%仅适用于数字。所以,你可以%通过每个数组的大小来获得一个索引,然后索引到数组中:

first = rank[rand()%13];
second = suit[rand()%4];
于 2012-10-17T04:26:44.007 回答
0
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

int main()

{
char rank[13] = {'a','2','3','4','5','6','7','8','9','t','j','q','k'};
char suit[4] = {'C','D','H','S'};
int first;
int second;

srand(time(NULL));

                first = rank[(rand()%13)];
                second = suit[rand()%4];

        printf("Your Card: %c %c", first, second);


return 0;
}

在您的printf声明中,您需要使用%c而不是%dsinceranksuit是字符数组。

于 2012-10-17T04:31:55.430 回答