[英]Garbage Result in my code
大家好,所以我正在研究可找到相同數字並顯示它們的代碼,到目前為止,結果只是我需要幫助的隨機數。
int main(void){
int arr[10] = {1, 2, 3, 4, 5, 4, 8 ,8, 9, 10};
int i;
int j;
int same[10];
int ctr = 0;
for(i = 0; i < 10; i++){
for(j = 10; j > 0;j--){
if(arr[i] == arr[j]){
same[ctr++] = arr[i];//store the similar numbers
}
}
}
for(i = 0; i < 10; i++){
printf("%d", same[i]);
}
getch();
return 0;}
從9開始第二個循環( j
循環),然后轉到0。
我在codechef編譯器上運行了您的代碼,它給出了運行時錯誤。 因為在您的ctr ++步驟中,ctr的值超出了數組same []的大小。
而且,在您的代碼中,您正在將一個元素與其自身進行比較,因此每個數字都將被打印在列表中(因為i == j可能是這種情況)
如果包含條件i!=j
或將j from i+1 to 9
迭代j from i+1 to 9
這樣最好不進行自我比較,那會更好。 以下是相同代碼的工作片段(您的for循環):-
for(i = 0; i < 10; i++){
for(j = 10; j > 0;j--){
if(arr[i] == arr[j] && i!=j){
same[ctr] = arr[i];//store the similar numbers
ctr++;
cout<<ctr<<" ";
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.