我一直在网站上寻找这个问题的可能答案,尽管它们都是相似的,但它们似乎与我的问题不完全一样,这就是为什么我被迫打开这个问题。所以我需要做一个骰子游戏,应该滚动2骰子范围从1-6和用户应该猜测的数字将是什么。然后,程序输出模具的值,如果猜测的值不是2模具的真实值,则输出reroll的值。如果是的话,程序就停止滚动模具,并告诉您模具需要多少卷才能达到您的猜测值。
由于某些原因,我的程序不断滚动模具一遍又一遍,没有停止,我不完全确定为什么。我试着在一个单独的程序中测试它,并且更加困惑为什么我仍然不能获得不同的值,即使srand()在main开头只被调用一次。(我意识到,在函数throwCalc1和不必要的throwCalc2中有一些问题)如果我试图将rand()放在变量之外,就会得到不同的值,但是如果我将它放在变量中,则值保持不变。我尝试让变量成为一个函数,但它仍然不能工作,因为编译器给了我一个错误,上面写着“初始化使指针从整数中而不是强制转换”
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}原节目:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}发布于 2013-11-27 04:40:07
现在,您正在循环中调用throwCalc1()和throwCalc2(),但放弃了结果。您需要将这些结果保存在一对变量中:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);在完成此操作之后,您可能会注意到,getcalc和getcalc2不需要成为该函数的参数--它们可以只是throwResult()中的局部变量。
此外,您的throwCalc1()和throwCalc2()函数是相同的,因此您可以删除它们,只需调用其余的函数两次。
您的测试函数应该如下所示:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}发布于 2013-11-27 04:40:03
您可以在main顶部执行一次此操作:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();然后,只需再次调用throwCalc1() &2,就可以期待这些值进行更新。
除了修复srand()之外,让throwCalc1 &2将值返回到局部变量中,而不是传递一些内容。
https://stackoverflow.com/questions/20233928
复制相似问题