C++ 查找列'右侧的最大元素;k';
我有一项任务,要求我查找列“k”右侧的max元素(据我所知,我需要在k+1列中查找最大值)。我显然做错了什么,因为当我运行代码时,max值等于0。一定是我错过了一个错误,所以任何帮助都将不胜感激。 这是我的代码:C++ 查找列'右侧的最大元素;k';,c++,arrays,algorithm,for-loop,max,C++,Arrays,Algorithm,For Loop,Max,我有一项任务,要求我查找列“k”右侧的max元素(据我所知,我需要在k+1列中查找最大值)。我显然做错了什么,因为当我运行代码时,max值等于0。一定是我错过了一个错误,所以任何帮助都将不胜感激。 这是我的代码: #include <iostream> #include <algorithm> #include <iomanip> using namespace std; int main() { int n,m,k; int max=-1000001;
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
int n,m,k;
int max=-1000001;
int a[10][10];
cin>>n>>k;
m=n;
for (int i=0;i<n;i++) {
for (int j=0;j<m;j++) {
cin>>a[i][j];
}
}
for(int i=0;i<n;i++)
{
for (int j=0;j<m+1;j++)
{
if(a[i][j]>max && a[i][j]!=max && j==k+1)
max=a[i][j];
}
}
if (k>=m)
cout<<"No";
else
cout<<max;
}
这是我应该得到的输出:
4
要获得所需的预期输出,只需编写
int max = a[0][k+1];
for ( int i = 1; i < n; i++ )
{
if ( max < a[i][k+1] ) max = a[i][k+1];
}
对于这个输入
3 2
程序应发出“否”,因为当k等于2时,k+1产生3,且3不是有效指数。此输入的有效索引范围为[0,2]
您可以使用我的答案中针对该输入提供的代码获得预期结果
3 1
当您使用调试器运行此程序时,它的行为与您预期的不同的第一点是什么?是的,它可以与所有其他输入完美配合,但我也需要此程序与“3 2”输入配合使用。有什么办法吗?@xdarkestshadow我已经在我的答案中写下了有效的索引范围是[0,2]。因此,使用索引2+1(=k+1)是无效的,并且会导致未定义的行为。是否需要未定义的行为?:)
3 2
3 1