具有可变长度的C ++数组不起作用

时间:2015-10-28 20:23:41

标签: c++

/*Print the first N prime numbers based on user input*/

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

bool isPrime(int N) {
   if (N <= 0) {return false;}
   double L = sqrt(N);
   for (int i=2; i<=L; i++) {
      if (N%i == 0) {return false;}
   }
   return true;
}

int main()
{
   int Q = 0;  //# of prime numbers to be found
   int C = 0;  //That's the counter
   int I = 2;  //Number to be check
   cout<<"Number of prime numbers needed: ";
   cin>>Q;

   int primes [Q];

   while (true) {
      if (C == Q) {break;}
      if (isPrime(I)) {
         primes[C] = I;
         C++;
         I++;
      }
   }

   for (int i=0; i<Q; i++) {
      cout<<primes[i]<<endl;
   }

   return 0;
}

这不起作用并且总是在屏幕上打印2和1而不是素数列表,isPrime函数运行良好,可能是我的数组有问题

2 个答案:

答案 0 :(得分:3)

只有当prime条件为真时,

I才会递增,如果是子句,则递增它:

while (true) {
    if (C == Q) {break;}
    if (isPrime(I)) {
        primes[C] = I;
        C++;
    }
    I++;  //here
}
  

具有可变长度的C ++数组不起作用

直到c变量不会超过整数范围或数组大小的堆栈帧。

答案 1 :(得分:0)

下面一行中的代码有编译错误

int primes [Q];

您必须使用以下行更改此内容

int *primes = new int[Q];