我沒有那麼多的C++經驗。在這裏,我聲明瞭兩個全局變量 n和cache.This是我的代碼相同。在C++中聲明全局變量的問題?
#include<iostream>
using namespace std;
#include<vector>
int n;
int cache[n][n];
int find_max_profit(vector<int> &v,int l,int r)
{
if(l>r)
{
return 0;
}
else
{
int year=l+n-r;
return max(find_max_profit(v,l+1,r)+year*v[l],find_max_profit(v,l,r-1)+year*v[r]);
}
}
int main()
{
cout<<"enter the number of wines"<<endl;
cin>>n;
int i,j;
cout<<"enter the prices"<<endl;
vector<int> v;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cache[i][j]=-1;
}
}
for(i=0;i<n;i++)
{
int num;
cin>>num;
v.push_back(num);
}
int max=find_max_profit(v,0,n-1);
cout<<"maximum profit is "<<max<<endl;
return 0;
}
當我編譯此代碼我收到以下錯誤:
||=== Build: Debug in selling wine (compiler: GNU GCC Compiler) ===|
/home/kaminey/makichut/selling wine/main.cpp|5|error: array bound is not an integer constant before ‘]’ token|
/home/kaminey/makichut/selling wine/main.cpp|5|error: array bound is not an integer constant before ‘]’ token|
/home/kaminey/makichut/selling wine/main.cpp||In function ‘int main()’:|
/home/kaminey/makichut/selling wine/main.cpp|29|error: ‘cache’ was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
但這應該被編譯,我想知道什麼是錯在這裏我的代碼。
是什麼'n的值'in int cache [n] [n];'? – silentboy
@silentboy n是輸入。 – user2738777
@ user2738777編譯時需要知道'n'的值。你不能在運行時神奇地擴展它。使用'std :: vector'或其他適當的東西。 –