c - 随机生成的数字不能与 while 循环一起正常工作

标签 c

我正在创建一个程序,它接受一个数字,该数字必须与两个骰子上的数字相加。例如:用户输入 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/

相关文章:

c - malloc 存储它的元数据

c - C中的 "this can never happen"错误类型应该如何处理?

c - O_WRONLY 未声明(首次在该函数中使用)

在指向数组的指针上调用 memset?

c - 有没有办法在不先读取磁盘扇区的情况下将几个字节写入磁盘扇区?

将字符串转换为字符 c

c - Bare-Metal C : Why are some IDEs startup files doing things crt0. s 无论如何都会处理?

c - OpenCV(C) : calculating moments FROM contour

c - Mac OS Sierra 上的 GDB,试图完全卸载和删除所有文件但不能

c - C 中的快速排序——指针和内存