为什么我的代码出现运行时错误
Why is my code giving Runtime Error?
我正在尝试制作一个Amazing Prime Series(APS),其中有一个向量myvectormyvector[0]=myvector[1]=0
对于n>1,myvector[n]=myvector[n-1]+f(n),其中f(n)是n的最小素因子。
输入3(测试用例数)
2
3
4
输出
2
5
7
#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
bool isPrime(int p)
{
int c=sqrt(p);
if(c==1)
{
return true;
}
else
{
for(int i=2;i<=c;i++)
{if(p%i==0)
{return false;}
else
{return true;}
}
}
}
int func(int n1)
{
if(n1%2==0)
{
return 2;
}
else
{
if(isPrime(n1)==true)
{
return n1;
}
else
{
int c1= sqrt(n1);
for(int i=2;i<=c1;i++)
{
if(n1%i==0 && isPrime(i)==true)
{
return i;
}
}
}
}
}
main()
{
int t;
std::vector<int> myvector;
myvector[0]=myvector[1]=0;
while(t--)
{
int n;
cin>>n;
while(n>1)
{
myvector[n]=myvector[n-1]+func(n);
cout<<myvector[n]<<endl;
}
}
}
您的向量为空,其中的任何索引都将越界,并导致未定义的行为。
一旦知道确切的大小,就需要调整向量的大小,或者根据需要推回元素。
向量的问题不在于你有唯一未定义的行为。您在未初始化的情况下使用局部变量t
,这意味着它的值将是不确定的,并且除了初始化它之外,以任何方式使用它也将导致UB。
用push_back()
:填充向量
auto main(int, char**) -> int // <- corrected function prototype
{
// this loop construct is ugly. use a for loop, when that is what you intent.
// int t = 42; // <- t was not initialized
// while(t--)
for(int t = 0; t < 42; t++)
{
int n;
cin >> n;
// we create a new vector in each run through the loop.
auto myvector = std::vector<int>{0, 0};
// your loop did never break, because you changed nothing of
// the condition inisde.
for(int i = 1; i < n; i++)
{
myvector.push_back(myvector.back() + func(i));
std::cout << myvector.back() << std::endl;
}
}
}
还请在循环中创建一个新的向量。或者,你也可以清除向量,但这在陈述意图方面有点弱。如果您尝试缓存以前计算过的值,请不要一次又一次地重新计算。
顺便说一下:您不需要存储序列的所有值:
auto main(int, char**) -> int
{
for(int t = 0; t < 42; t++)
{
int n;
cin >> n;
int current = 0;
for(int i = 1; i < n; i++)
{
current += func(i);
std::cout << current << std::endl;
}
}
}
这不仅更短,而且可能更快,因为CPU可以将current
保存在寄存器中,因此不必加载和存储相对较慢的内存。
注意:所有代码都未经测试,可能包含更多错误。
相关文章:
- 为什么此代码存在运行时错误?
- 蝴蝶代码 88.合并排序数组 c++ 运行时错误
- 在Hackerearth上获取运行时错误(SIGSEGV),无法找出代码中的问题
- 为什么我在此代码中收到运行时错误
- 我的代码上的运行时错误 sigsegv
- 矢量的 c++ 代码中的运行时错误
- C++代码在 for 循环的条件下给出运行时错误,而如果它被具有相同意义的代码替换,则编译正确
- 我的代码中出现运行时错误的可能原因是什么?
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 在计算机级别,应用程序以二进制方式运行,然后当发生运行时错误时,它如何呈现回错误代码
- .NET CORE 2 DLL引用带有C 代码运行时错误
- 为什么我的代码给出运行时错误超时
- 为什么我的程序在删除以下代码中的注释后会出现运行时错误?
- 薄板样条形状转换运行时错误 [使用代码 -1073741819 退出]
- C 代码的运行时错误(基于指针)
- 代码中的运行时错误,用于求解最小的偶数可整除
- 为什么我的代码导致运行时错误
- 为什么矢量上的这段代码会给出运行时错误
- 涉及向量的初学者代码,SEIGSEV运行时错误
- 为什么这段代码会产生运行时错误