#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>> n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
cout<<a[j]<<" ";
}
cout<<endl;
}
int sum=0;
int mx=INT_MIN;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
for(int k=i;k<=j;k++)
sum += a[k];
mx = max(mx,sum);
cout<<endl;
}
}
}
cout<<mx;
return 0;
}
编译器给出了这三个错误。
MaxSubArrSum.cpp:40:5: error: 'cout' does not name a type
40 | cout<<mx;
| ^~~~
MaxSubArrSum.cpp:41:5: error: expected unqualified-id before 'return'
41 | return 0;
| ^~~~~~
MaxSubArrSum.cpp:42:1: error: expected declaration before '}' token
42 | }
| ^
我觉得如果第二个问题得到解决,第三个问题会自行解决吗?cout和return的引用表明这是一个常见的语法错误。不过,我试着通过适当地放置空格和括号来保持代码尽可能干净。
在cout<lt;mx;。一些其他反馈和这里的固定版本:
- 为什么我不应该#include<bits/stdc++.h>
- 为什么";使用命名空间std"被认为是不好的做法
//#include<bits/stdc++.h> <== don't do this
//using namespace std; <== don't do this either
#include <iostream>
#include <vector> // for dynamically resizable arrays
#include <limits>
int main()
{
int n;
std::cout << "how many values do you want to enter : "; // give info to user!
std::cin >> n;
// int a[n]; // this is NOT valid C++
// for dynamically allocatable arrays use std::vector
std::vector<int> a;
for (int i = 0; i < n; i++)
{
int value;
std::cout << "enter value : "; // give info to user!
std::cin >> value;
a.push_back(value); // add value to array
}
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
std::cout << a[j] << " ";
}
std::cout << "n"; // avoid std::endl
}
int sum = 0;
//int mx = INT_MIN; <== "C" style
int mx = std::numeric_limits<int>::min();
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
for (int k = i; k <= j; k++) sum += a[k];
mx = std::max(mx, sum);
}
}
std::cout << mx;
return 0;
}