我创建了这段代码来解决一些有效的在线答案,但我想知道以这种方式分配动态内存是否可以。数组大小在整个循环中连续定义。没事吧?
#include <iostream>
using namespace std;
int main ()
{
int sum=0;
int x;
int *ptr = new int[x];
ptr[0]=1;
ptr[1]=2;
int max = 4000000;
int i=2;
while (ptr[i-2]<max)
{
ptr[i]=ptr[i-1]+ptr[i-2];
i++;
}
// now we use (i -1) as the last array fill b/c i is bigger than 4 000 000
// sort with val % 2 == 0 !modulus!
for (int j=0; j<(i-1); j++) {
if (ptr[j]%2==0) {
sum+=ptr[j];
}
}
delete[] ptr;
cout<<sum;
return 0;
}