[英]C program - find largest sequence in array
给出这个例子:
int arr[3][7] = { {1,0,0,1,1,1,1}, //should output 4
{0,1,1,1,1,0,1}, //should output 4
{0,0,1,1,1,1,1}}; //should output 5
查找包含数字1的最大序列,并打印行索引和数字1 。
不要 在每行中 计算总数 1 。 只有他们一个接一个 。
这是我的方法:
int main(){
int i,j,c=0,count=0;
int arr[3][7] = { {1,0,0,1,1,1,1}, //output 4
{0,1,1,1,1,0,1}, //output 4
{0,0,1,1,1,1,1}}; // output 5
for(i=0; i<3; i++){
for(j=0; j<7; j++){
if(arr[i][j] == 1){
c++;
} else if( arr[i][j] == 0 && c > count ) {
count = c;
c = 0;
}
}
printf("%d\n", count);
}
return 0;
}
我现在想要得到的输出是4,4,5,但是我正在得到1,4,5。
解决方案感谢https://stackoverflow.com/users/1228887/twain249
int main(){
int i,j,c=0,count=0;
int arr[3][7] = { {1,1,0,1,1,1,1}, //output 4
{0,1,1,1,1,0,1}, //output 4
{0,0,1,1,1,1,1}}; // output 5
for(i=0; i<3; i++){
for(j=0; j<7; j++){
if(arr[i][j] == 1){
c++;
} else {
count = c;
c = 0;
}
}
if(c > count){
count = c;
}
printf("%d\n", count);
c=0;
}
return 0;
}
您忘记处理最长序列在列表结尾的情况
在内部j
循环之后,添加以下内容
if (c > count) {
count = c;
}
您也忘记在每次检查后添加透明纸。
打印输出后添加
c = clear = 0;
编辑:另外1个错误。 即使新序列不是最长的,也需要重置c
。
如果更改为else
else if (arr[i][j] == 0) { // If isn't necessary if 0/1 are your only options
{
if (c > count) {
count = c;
}
c = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.