【问题标题】:Why is my code giving Runtime Error?为什么我的代码给出运行时错误?
【发布时间】:2015-11-11 08:47:58
【问题描述】:

我正在尝试制作一个惊人的 Prime 系列(APS),其中有一个向量 myvector 我的向量[0] = 我的向量[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 没有初始值,并且要通过索引访问向量,您需要 std::vector myvector (10); // 10 个零初始化元素

标签: c++ numbers primes prime-factoring


【解决方案1】:

您的向量为空,其中的任何索引都将超出范围并导致未定义的行为

知道确切大小后,您要么需要resize 向量,要么根据需要push back 元素。


并且向量的问题不在于您所拥有的唯一未定义行为。您使用局部变量t 而不对其进行初始化,这意味着它的值将是indeterminate,并且除了初始化之外以任何方式使用它也会导致UB。

【讨论】:

  • 向量不需要定义大小。我想,你是想说:“你的向量是空的”。
  • 我想要一个动态大小..我该怎么做?
  • @cdonat 我正在填充向量中的值..是否有必要在声明时对其进行初始化然后覆盖这些值?
【解决方案2】:

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 保存在寄存器中,因此不必加载和存储相对较慢的内存。

注意:所有代码都未经测试,可能包含更多错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多