#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main()
{
printf("\n1");
srand ((unsigned)time(NULL));
printf("\n1");
struct node {
int Digi;
struct node *Prev;
struct node *Next;
};
printf("\n1");
struct node Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Num10,NumAdd;
Num1.Digi = rand() % 100;
Num1.Prev = NULL;
do {
Num2.Digi = rand() % 100;
} while ((Num2.Digi < Num1.Digi) || (Num2.Digi == Num1.Digi));
Num2.Prev = &Num1;
Num1.Next = &Num2;
do
Num3.Digi = rand() % 100;
while ((Num3.Digi < Num2.Digi) || (Num3.Digi == Num2.Digi));
Num3.Prev = &Num2;
Num2.Next = &Num3;
do
Num4.Digi = rand() % 100;
while ((Num4.Digi < Num3.Digi) || (Num4.Digi == Num3.Digi));
Num3.Prev = &Num4;
Num3.Next = &Num3;
do
Num5.Digi = rand() % 100;
while ((Num5.Digi < Num4.Digi) || (Num5.Digi == Num4.Digi));
Num5.Prev = &Num4;
Num4.Next = &Num5;
do
Num6.Digi = rand() % 100;
while ((Num6.Digi < Num5.Digi) || (Num6.Digi == Num5.Digi));
Num6.Prev = &Num5;
Num5.Next = &Num6;
do
Num7.Digi = rand() % 100;
while ((Num7.Digi < Num6.Digi) || (Num7.Digi == Num6.Digi));
Num7.Prev = &Num6;
Num6.Next = &Num7;
do
Num8.Digi = rand() % 100;
while ((Num8.Digi < Num7.Digi) || (Num8.Digi == Num7.Digi));
Num8.Prev = &Num7;
Num7.Next = &Num8;
do
Num9.Digi = rand() % 100;
while ((Num9.Digi < Num8.Digi) || (Num9.Digi == Num8.Digi));
Num8.Prev = &Num9;
Num9.Next = &Num8;
do
Num10.Digi = rand() % 100;
while ((Num10.Digi < Num9.Digi) || (Num10.Digi == Num9.Digi));
Num10.Prev = &Num9;
Num9.Next = &Num10;
Num10.Next = NULL;
printf("\n1");
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
Num1.Digi, Num2.Digi, Num3.Digi, Num4.Digi, Num5.Digi,
Num6.Digi, Num7.Digi, Num8.Digi, Num9.Digi, Num10.Digi);
}
程序很少运行到最后。但是在打印出2“1”后它总是卡住。有时它运行正常并显示10个数字。但它最有可能被卡住了。我知道有一些循环,但它们不会导致程序卡住这么长时间。我们现在都拥有快速的计算机。所以有人知道为什么会被卡住吗?
答案 0 :(得分:1)
您构建循环的方式,如果在最后一个循环之前的任何接受的随机数是99
,则其余循环都不能终止,因为新的可接受数字不能小于{{1} },或等于99
,或大于99
。
生成一个填充了唯一随机数的数组可能更简单,排序,然后将这些数据读入99
。请注意,struct
函数会传递已添加到列表中的随机数的计数,以便只搜索这些数字。
in_list()
示例输出:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool in_list(int num, int arr[], size_t list_sz)
{
size_t i;
for (i = 0; i < list_sz; i++) {
if (arr[i] == num) {
break;
}
}
return i < list_sz ? true : false;
}
int compare(const void *x, const void *y) {
const int *cx = (const int *) x;
const int *cy = (const int *) y;
return (*cx > *cy) - (*cx < *cy);
}
int main(void)
{
int random_numbers[10];
int num;
srand(time(NULL));
for (size_t i = 0; i < 10; i++) {
do {
num = rand() % 100;
}while (in_list(num, random_numbers, i));
random_numbers[i] = num;
}
qsort(random_numbers, 10, sizeof(int), compare);
for (size_t i = 0; i < 10; i++) {
printf("%d\n", random_numbers[i]);
}
return 0;
}