我正在创建一个程序,它接受一个数字,该数字必须与两个骰子上的数字相加。例如:用户输入 9,然后输入 6+3。这两个数字随机生成,一直生成,直到等于用户输入的数字。 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int totalSought;
int count = 0;
time_t totalTime;
printf("Game of Dice \n");
printf("============ \n");
printf("Enter total sought: ");
scanf("%d", &totalSought);
//if totalsought is higher than 12 the loop keeps asking to re-enter!
if (totalSought > 12) {
printf("** Invalid Input! Try Again! **\n");
while (totalSought > 12) {
printf("Enter total sought: ");
scanf("%d", &totalSought);
}
}
//loads random number generator
srand((unsigned) time(&totalTime));
//this loop checks if rand generates 2 random added equal to totalsought-
//if not equal they keep generating until it equals!
while (rand() % 7 + rand() % 7 != totalSought) {
count++;
printf("Result of the throw %d: %d \n",count, rand() % 7 + rand() % 7 );
}
}
但是当我编译并运行程序时,它并没有停止到我输入的数字。
Game of Dice
============
Enter total sought: 5
Result of the throw 1: 5
Result of the throw 2: 11
Result of the throw 3: 7
Result of the throw 4: 4
Result of the throw 5: 6
它应该在第一次抛出时停止,但它没有。 如何修复此错误?
最佳答案
循环
while (rand() % 7 + rand() % 7 != totalSought) {
count++;
printf("Result of the throw %d: %d \n",count, rand() % 7 + rand() % 7 );
}
表示:创建两个随机数,将它们相加。如果总和等于totalSought
,则跳出循环;否则再创建两个(完全不相关的)随机数并打印它们的总和。
关于c - 随机生成的数字不能与 while 循环一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33511363/