gpt4 book ai didi

c++ - C++中的定时发生器

转载 作者:行者123 更新时间:2023-11-28 07:46:24 24 4
gpt4 key购买 nike

我完成了素数生成程序。现在,我想测试所有素数所需的时间并将这些数字存储在一个数组中。我写了这段代码....

#include <iostream>
#include <ctime>
using namespace std;

int main ()
{


int long MAX_NUM = 1000000;
int long MAX_NUM_ARRAY = MAX_NUM+1;
int long sieve_prime = 2;
int long sieve_prime_constant = 0;
int time_store = 0;
int *Num_Array = new int[MAX_NUM_ARRAY];
std::fill_n(Num_Array, MAX_NUM_ARRAY, 3);
Num_Array [0] = 1;
Num_Array [1] = 1;

while (time_store<=100)
{
clock_t time1,time2;
time1 = clock();
while (sieve_prime_constant <= MAX_NUM_ARRAY)
{
if (Num_Array [sieve_prime_constant] == 1)
{

sieve_prime_constant++;
}
else
{
Num_Array [sieve_prime_constant] = 0;
sieve_prime=sieve_prime_constant;
while (sieve_prime<=MAX_NUM_ARRAY - sieve_prime_constant)
{
sieve_prime = sieve_prime + sieve_prime_constant;
Num_Array [sieve_prime] = 1;
}
if (sieve_prime_constant <= MAX_NUM_ARRAY)
{
sieve_prime_constant++;
sieve_prime = sieve_prime_constant;
}
}
}
time2 = clock();
delete[] Num_Array;
cout << "It took " << (float(time2 - time1)/(CLOCKS_PER_SEC)) << " seconds to execute this loop." << endl;
cout << "This loop has already been executed " << time_store << " times." << endl;
float Time_Array[100];
Time_Array[time_store] = (float(time2 - time1)/(CLOCKS_PER_SEC));
time_store++;
}


return 0;

}

当我运行它时,程序似乎经历了一次长循环然后崩溃了。出了什么问题,我该如何解决?

最佳答案

你在第一个循环结束时删除了你的 numArray,所以当你再次循环时你引用了 NULL...

不确定您打算用 delete[] 语句做什么......但是无论您打算做什么 - 要么在其他地方做,要么做其他事情,或者重新初始化数组,或者……你无疑可以从这里算出来。

关于c++ - C++中的定时发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802815/

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