我想做的是对sumDices()
函数中打印的随机骰子求和,但是我不知道该怎么做,有人可以帮我吗?
这是我的代码的样子:
void printDices() {
int i = 0;
int total = 0;
char one[3][3] = { { ' ',' ','\n' },{ ' ','*','\n' },{ ' ',' ','\0' } };
char two[3][4] = { { '*',' ',' ','\n' },{ ' ',' ',' ','\n' },{ ' ',' ','*','\0' } };
char three[3][4] = { { '*',' ',' ','\n' },{ ' ','*',' ','\n', },{ ' ',' ','*','\0' } };
char four[3][4] = { { '*',' ','*','\n' },{ ' ',' ',' ','\n' },{ '*',' ','*','\0' } };
char five[3][4] = { { '*',' ','*','\n' },{ ' ','*',' ','\n' },{ '*',' ','*','\0' } };
char six[3][4] = { { '*',' ','*','\n' },{ '*',' ','*','\n' },{ '*',' ','*','\0' } };
for (i = 0; i < 5; i++)
{
switch (rand() % 5) {
case 0: printf("%s\n", one); break;
case 1: printf("\n%s\n", two); break;
case 2: printf("\n%s\n", three); break;
case 3: printf("\n%s\n", four); break;
case 4: printf("\n%s\n", five); break;
case 5: printf("\n%s\n", six); break;
}
}
}
int sumDices() {
return 0;
}
int main(void) {
printDices();
srand(time(0));
sumDices();
system("pause");
return 0;
}
最佳答案
您可以将这些字符数组设置为
char one[3][3] = { { ' ',' ','\n' },{ ' ','*','\n' },{ ' ',' ','\0' } };
至
char one[3][3] = {" \n", " *\n", " \0"};
增强可读性。如here所述,写出数组界限似乎不是问题。
您可以创建变量
sum
来查找随机数之和,例如int sum=0, n;
for (i = 0; i < 5; i++)
{
n=rand()%5;
sum+=n;
switch (n) {
case 0: printf("%s\n", one); break;
case 1: printf("\n%s\n", two); break;
case 2: printf("\n%s\n", three); break;
case 3: printf("\n%s\n", four); break;
case 4: printf("\n%s\n", five); break;
case 5: printf("\n%s\n", six); break;
}
}
return sum;
为此,您需要将
printDice()
函数的返回类型设置为int
int printDices()
要获取
printDices()
中sumDices()
返回的值,请在printDices()
中调用sumDices()
。在循环中,您打印的值比
rand()
获得的随机数大1。也许您需要这些值的总和。在这种情况下,您可以for (i = 0; i < 5; i++)
{
n=rand()%5+1;
sum+=n;
switch (n) {
case 1: printf("%s\n", one); break;
case 2: printf("\n%s\n", two); break;
case 3: printf("\n%s\n", three); break;
case 4: printf("\n%s\n", four); break;
case 5: printf("\n%s\n", five); break;
case 6: printf("\n%s\n", six); break;
}
}
即,将
1
添加到rand()
返回的随机值中。这样,值将在1
和6
之间并包括在内。编辑:
您试图使用
printf()
中的switch()
语句打印多维数组。您必须一张一张地打印它们。
或者,如@Steve所指出的那样,将这些多维字符数组变成一维数组,例如
char one[]=" \n *\n \0";
正如Bathsheba所说,
case 5:
中的switch
将永远不会到达。我认为您需要rand()%6
而不是rand()%5
。毕竟,一个骰子有6个面。
关于c - 如何对函数c中的随机数求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503045/