简体   繁体   中英

C++ array with variable length wouldn't work

/*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;
}

This does not work and always print 2 and 1 to the screen instead of a list of prime numbers, the isPrime function does work well, probably something wrong with my array

I will increment only when prime condition is true, increment it outside if clause:

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

C++ array with variable length wouldn't work

It works until c variable dosn't crosses integer range or array size the stack frame.

Your code in below line has compiler error

int primes [Q];

you must change this with below line

int *primes = new int[Q];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM