C程序运行时卡住

标签 c

好吧,我用 c 语言编写了一个程序,要求用户选择他想玩的 4 个阶段中的 1 个。用户选择阶段后,程序将生成一个由 4 个字符组成的密码,其范围为 1-6(例如 3516)。 但我想让字符不重复,这样就不会有两个相同的数字(例如,1642 是好的代码,但 6632 是坏代码)。 当我在代码中做了几个“if”并运行它后,它就堆积起来了。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int getStages();
int randCode();

int main()
{
    getStage();

    system("PAUSE");
}

int getStage()
{

    int choice= 0;

    printf("What stage would you like to choose? Choose Wisely: ");
    scanf("%d", &choice);

    randCode();
}

int randCode()
{
    srand(time(NULL));

    int randFirst= rand() % 6 + 1;
    int randSecond= rand() % 6 + 1;
    int randThird= rand() % 6 + 1;
    int randFourth= rand() % 6 + 1;

     while(randFirst = (randSecond || randThird || randFourth))
     {
         int randFirst= rand() % 6 + 1;
     }

     while(randSecond = (randFirst || randThird || randFourth))
     {
         int randSecond= rand() % 6 + 1;
     }

     while(randThird = (randFirst || randSecond || randFourth))
     {
         int randThird= rand() % 6 + 1;
     }

     while(randFourth = (randFirst || randSecond || randThird))
     {
         int randFourth= rand() % 6 + 1;
     }

    char firstNumber= randFirst;
    char secondNumber= randSecond;
    char thirdNumber= randThird;
    char fourthNumber= randFourth;

    printf("%d %d %d %d\n", firstNumber, secondNumber, thirdNumber, fourthNumber);


}

最佳答案

您在循环内本地声明变量randFirstrandFourth,并用您拥有的相同名称隐藏其他变量。您在循环中分配的值仅分配给这些循环局部变量。

这当然会对循环条件产生影响(一旦修复它们),因为循环条件将使用函数局部变量。如果您进入一个循环,该循环将是无限的。

关于C程序运行时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34673358/

相关文章:

c - 从 fds_bits 中提取文件描述符

c - 在 C 中获取 union 成员的地址是否合法?

objective-c - iOS NSString stringWithUTF8String/NSString initWithCString 错误utf8解码

c - 我在指针和动态数组方面遇到了困难

Python Ctypes 传入指针并返回结构

c - 如何知道绑定(bind)对中的事件从接口(interface)

C - 不能将 strcpy 与 strtok 一起使用

c - printf() 在 x86-64 平台上给出相同的输出,即使在交换参数时也是如此

c - Linux 上的可执行文件如何知道从哪里获取数据文件?

结构中元素的 C 顺序