Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C语言中以随机顺序打印数字1-10而不重复_C_Loops_Random - Fatal编程技术网

如何在C语言中以随机顺序打印数字1-10而不重复

如何在C语言中以随机顺序打印数字1-10而不重复,c,loops,random,C,Loops,Random,我需要能够打印数字1-10在随机顺序在C。 多谢各位 这是我的尝试 #include <stdio.h> #include <time.h> #include <stdlib.h> int main () { int arr[100]; int size=8; srand(time(NULL)); for (int i=0; i<=size; ++i){ arr[i]=rand()%size+1;

我需要能够打印数字1-10在随机顺序在C。 多谢各位

这是我的尝试

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

int main ()
{
    int arr[100];
    int size=8;
    srand(time(NULL));
    for (int i=0; i<=size; ++i){
        arr[i]=rand()%size+1;
            for (int j=0; j<=i; ++j){
                if (arr[i]==arr[j]){
                    arr[i]=rand()%size+1;
                }
            }
        }
    for (int count=0; count<size; ++count){
        printf("%d\n",arr[count]);
    }
    return 0;
}
#包括
#包括
#包括
int main()
{
int-arr[100];
int size=8;
srand(时间(空));

对于(inti=0;i通常,这个网站的工作方式是,你展示你做了什么,你说什么不起作用,我们从那里开始

看到您的问题,有两种可能:要么您希望我们编写代码(我不会这么做),要么您根本不知道如何开始

我将采用第二种方法,并就如何处理您的问题为您提供一个起点:

首先创建一个列表,包含从1到10的所有数字,并跟踪该列表中元素的数量(称之为
lSize
)。然后生成一个介于0和
lSize
之间的随机数(可以使用
random()*lSize
,向下舍入)。这将为您提供可能获取的号码的索引。您获取列表中该索引上的号码,然后将其从列表中删除

让我用一个例子来说明它是如何工作的:

list : (1,2,3,4,5,6,7,8,9,10)
lSize : 10
final_list : <empty>
第二次迭代:假设
random()*lSize
,四舍五入,等于8

list[8] = 10
Remove it and add it to the final_list:

list : (1,2,3,5,6,7,8,9)
lSize : 8
final_list : (4,10)
从那里继续,直到列表为空或
lSize
为零

谨防:代码>列表最好是一个链表而不是一个数组,因为在中间某个元素的移除会导致其他元素被移位。在数组中,这是困难的;在链表中,这是微不足道的。


祝你好运

你能从一个数组中按顺序打印数字1-10吗?你能将数组随机排列吗?你能打印随机排列的数组吗?提示有10个!不同的序列。这回答了你的问题吗?抱歉,我在问题中添加了我的尝试
list[8] = 10
Remove it and add it to the final_list:

list : (1,2,3,5,6,7,8,9)
lSize : 8
final_list : (4,10)