[英]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.