所以,我一直在尝试对这个游戏进行编程,用户必须在其中输入他想要玩的分数。我想用数组来做这件事,所以我做了你在下面看到的(score[4] = {0, 0, 0, 0}
)。
但不知何故,当我使用 score[relplayers(数组中的一个计数器,所以程序通过轮次)] = score[relplayers](旧分数)+ 抛出(我掷骰子的值)时;我不知道为什么这不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int throwing () {
srand(time(NULL));
int value = rand() % 6 + 1;
return value;
}
int main() {
int abplayers, relplayers, thrown, playersshown, abscore, rounds;
printf("Enter the number of fields: ");
scanf("%d", abscore);
int score [4] = {0, 0, 0, 0};
for (rounds = 0; rounds < 50; rounds++)
{
for(relplayers = 0; relplayers < 4; relplayers++)
{
int playershown = relplayers + 1;
getchar();
thrown = throwing();
printf("nPlayer nº%d threw a %d", playershown, thrown);
score[relplayers] = score[relplayers] + thrown;
printf("nPlayer nº%d is in %d field", playershown, score);
if (score[relplayers] >= abscore)
{
printf("Player nº%d won", playershown);
exit(EXIT_FAILURE);
}
}
}
}
该程序的另一个问题是特殊字段。我想包括这些字段,以便玩家被困在这些字段中或在这些字段中得到提升。我试图把它放在我的程序中,但它似乎不起作用。
int enter() {
int allscore;
printf("Number of fields: ");
scanf("%d", allscore);
return allscore;
}
int badfields () {
int abscore;
srand(time(NULL));
abscore = enter();
int numbers[10] = {rand() % abscore + 1};
return numbers;
}
int goodfields () {
int abscore;
srand(time(NULL));
abscore = enter();
int fields[10] = {rand() % abscore + 1};
return fields;
}
int main()
...
if (score[relplayers] == goodfields())
{
printf("Player %d is boosted 5 fields backwards", playershown);
score[relplayers] = score[relplayers] - 5;
}
if (score[relplayers] == goodfields())
{
printf("Player %d is boosted 5 fields forwards", playershown);
score[relplayers] = score[relplayers] + 5;
}
这是C,不是C++。我假设你真的想要C。
我发现了以下问题:
你用错scanf
。例如。如果allscore
是整数, scanf("%d", allscore);
应该是scanf("%d", &allscore);
(scanf
与这里的printf
不同)。
srand
播种PRNG。在许多情况下,这应该在整个程序中只执行一次。不是在每个函数中使用随机数。改变它,因为它会影响数字的随机性。
如果你没有充分的理由在main中使用exit(EXIT_FAILURE);
,那就不要这样做。这是exit
,在我看来,你的案子并不是失败的。使用 return EXIT_SUCCESS;
.在 main 结束时,也应该有返回(对于循环完成而没有中止的情况)。
在《badfields
与goodfields
》中,你正在做一些非常奇怪的事情。
int badfields () {
...
int numbers[10] = {rand() % abscore + 1};
return numbers;
}
这到底是怎么回事?如果你想要一个由 10 个随机数组成的数组,初始化是错误的,更重要的是你返回一个地址而不是一些生成的随机数。下一个问题是numbers
是本地的;如果您打算返回多个值,您在这里也会遇到问题。