gpt4 book ai didi

c - 如何在循环中生成随机数,然后每 1000000 个数字将其存储在文件中?

转载 作者:行者123 更新时间:2023-11-30 20:30:47 25 4
gpt4 key购买 nike

所以基本上,在无限循环中,我必须生成随机数。然后,我必须在迭代中创建文件,其中第一个循环中是 file1.txt,第二个循环中是 file2.txt 等等。我们使用文件来存储生成的每 1000000 个随机数,因此 file1.txt 存储前 100 万个数字,file2.txt 存储接下来的 100 万个数字,依此类推。但我认为我搞砸了代码。你能帮我吗?

int rng(){
int i;
FILE *fptr;
int k = 0;

char buffer[32];
snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);
fptr=fopen(buffer, "wb");
for(i=0; i<1000000; i++)
{
fprintf(fptr, "%d", (rand() * rand()) % 1000001);
}
fclose(fptr);
k++;
}

最佳答案

您可以使用 while(1) 进行无限循环,然后使用简单的计数器来计算当前文件中的元素数量。

喜欢:

#include <stdio.h>

#define ELEMENTS_PER_FILE 5

int main(void) {
unsigned k = 0;
unsigned file_number = 1;

printf("Open file%u.txt\n", file_number);

while(1)
{
if (k == ELEMENTS_PER_FILE)
{
++file_number;
printf("Open file%u.txt\n", file_number);
k = 0;
}

++k;
printf(" Add random number #%u to file\n", k);

}

return 0;
}

输出:

Open file1.txt
Add random number #1 to file
Add random number #2 to file
Add random number #3 to file
Add random number #4 to file
Add random number #5 to file
Open file2.txt
Add random number #1 to file
Add random number #2 to file
Add random number #3 to file
Add random number #4 to file
Add random number #5 to file
Open file3.txt
Add random number #1 to file
Add random number #2 to file
. . .

您需要做的就是将 printf 替换为执行打印内容的代码。

使用函数生成单个文件,可以更好地组织代码。喜欢:

#include <stdio.h>

#define ELEMENTS_PER_FILE 5
#define FILES_TO_GENERATE 3

void make_file(unsigned num)
{
int i;
printf("Open file%u.txt\n", num);
for (i=1; i <= ELEMENTS_PER_FILE; ++i)
{
printf(" Add random number #%d to file\n", i);
}
printf("Close file%u.txt\n", num);
}

int main(void) {
unsigned file_number = 1;

while(file_number <= FILES_TO_GENERATE) // or while(1) if you really want infinite
{
make_file(file_number);
++file_number;
}

return 0;
}

输出:

Open file1.txt
Add random number #1 to file
Add random number #2 to file
Add random number #3 to file
Add random number #4 to file
Add random number #5 to file
Close file1.txt
Open file2.txt
Add random number #1 to file
Add random number #2 to file
Add random number #3 to file
Add random number #4 to file
Add random number #5 to file
Close file2.txt
Open file3.txt
Add random number #1 to file
Add random number #2 to file
Add random number #3 to file
Add random number #4 to file
Add random number #5 to file
Close file3.txt

关于c - 如何在循环中生成随机数,然后每 1000000 个数字将其存储在文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349083/

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