例如,給定一個方陣,找出正在增長的子串的長度。
matrix | result because of
5 |
1 2 3 4 5 |
2 5 2 5 9 |
7 8 9 0 1 --> 5 --> 1 2 3 4 5
0 0 0 0 0 |
2 3 6 1 2 |
我嘗試a[i][j]與a[i][j 1]計數器進行比較并增加計數器,但我認為我的問題是程式在最后一個元素上并且它不增加計數器。在這里,我有我的代碼:
int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n];
for(i = 0;i < n;i ){
for(j = 0;j <n;j ){
scanf("%d",&a[i][j]);
}
}
int max=-9999;
int counter;
for(i = 0;i < n;i ){
counter=0;
for(j = 0;j <n;j ){
if(a[i][j]<a[i][j 1]){
counter ;
}
if(counter>max){
max = counter;
}
}
}
printf("%d",max);
return 0;
}
uj5u.com熱心網友回復:
對于初學者來說,因為索引的范圍不能為負,所以將變數 max 宣告為負值是沒有意義的
int max=-9999;
它至少可以像
int max = 0;
在這個 if 陳述句中
if(a[i][j]<a[i][j 1]){
由于運算式 ,當i和j等于時,可以訪問超出分配陣列的記憶體。n - 1a[i][j 1]
還有這個 if 陳述句
if(counter>max){
max = counter;
}
應該移到內部 if 陳述句之外。
并且變數計數應該在外回圈中宣告
您可以通過以下方式重寫內部 for 回圈
int counter=1;
for(j = 1;j <n;j ){
if(a[i][j-1]<a[i][j]){
counter ;
}
}
if(counter>max){
max = counter;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378651.html
