gpt4 book ai didi

c - 如何判断每个随机数是否命中错误

转载 作者:行者123 更新时间:2023-11-30 17:44:48 26 4
gpt4 key购买 nike

所以我正在编写一个程序,需要生成一组从 1 到用户输入的某个数字的随机数。然后通过生成的随机数确定 1 到 N 中每个数字被击中的近似概率。所以对于我的代码:-

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

int main(void)
{
printf("Enter a number");
int input;
scanf("%d",&input);
getRandomIntFrom0ToK(input);
return 0;
}

void getRandomIntFrom0ToK (int K)
{
int i;
int j;
int a[2][K+1];
int b[999][999];
int counter=0;

srand(time(NULL));

for (i=0;i<K;i++) //Here I am storing the random numbers and indexes of each number
{
a[0][i] = i;
a[1][i]=rand()%K;

}

for(i=0;i<K;i++)//In another array transferring the indexes from the first array
{
b[0][i]=a[0][i];
}
for(i=0;i<K;i++)//Setting the second column of array b to 0
{
b[1][i]=0;

}


for(i=0;i<K;i++)//Running two for loops to check in array a if any of the values from the index are equal to any of the random numbers in the second column
{
for(j=0;j<K;j++)
{

if(a[0][i]==a[1][j])//If they are then make the index of array b corresponding to the number equal to 0+1, I will eventually add a certain probability but for now I just want to see that it works
{
b[1][i]=b[1][i]+1;

}
}
}//Up till here if I run the program, it works

/*for(i=0;i<K;i++)
{
printf("%d\n",b[0][i]);
}*/

}

所以问题是,当包含 b 数组的 printf 语句时,程序无法运行。我知道我的代码效率很低,但我只想知道我做错了什么。最终我想要做的是打印出 b 数组的两列,以便它在屏幕上输出我将使用 (1/K*100) 执行的数字和相应的百分比。谢谢,任何形式的帮助将不胜感激。

最佳答案

2个问题:缺少原型(prototype)和过度使用堆栈空间。

OP 调用 getRandomIntFrom0ToK(input); 而不先声明它。不太可能是一个主要问题。这个问题很能说明问题,因为它会导致典型的警告。这意味着编译器警告被忽略或未完全启用。

void getRandomIntFrom0ToK (int K);
int main(void) {
...
getRandomIntFrom0ToK(input);
return 0;
}

OP 创建了一个变量,这可能是一个问题。奇怪的是,小得多的一个就足以满足OP的帖子了。如果没有 printf("%d\n",b[0][i]),编译器可能会优化此变量,因为它的值永远不会被读取,只会被赋值。由于此变量有数百万字节长,因此它的存在(或不存在)可能会对代码操作产生重大影响,因为堆栈空间通常比通过 malloc() 获得的空间更加有限。

void getRandomIntFrom0ToK (int K) {
...
// b is maybe millions of bytes
// int b[999][999];
// Code only uses b[0][...] and b[1][...]
int b[2][999];

如果确实需要b[999][999],建议使用malloc()来提供空间。

关于c - 如何判断每个随机数是否命中错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19842888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com