2017-10-10 19 views
0

它應掃描10個整數,然後向後顯示它們,將偶數除以2,但只是顯示它們而不分割。爲什麼我的程序不會將偶數除以二?

ES:
10 9 8 7 6 5 4 3 2 1 ==> 1 2 3 2 5 3 7 4 9 5
但礦的作用: 10 9 8 7 6 5 4 3 2 1 == > 1 2 3 4 5 6 7 8 9 10

#include <stdio.h> 

int main(void) 
{ 
    int a[10]; 

    for(int i = 0; i < 10; i++) 
     scanf("%d", &a[i]); 

    for (int i = 0; i < 10; i++) { 
     if (a[i] % 2 == 0) { 
      a[i] = a[i]/2; i++; 
     } 
     else 
      i++; 
    } 

    for(int i = 9; i > -1; i--) 
     printf("%d\n", a[i]); 

    return 0; 
} 
+2

[如何調試小鐠(https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) –

回答

2

中間環路錯誤地遞增i兩次每次迭代:

for (int i = 0; i < 10; i++) { // <<== One increment 
    if (a[i]%2 == 0) { 
     a[i] = a[i]/2; i++; // <<== Another increment - first branch 
    } 
    else 
     i++;     // <<== Another increment - second branch 
} 

在你的情況下,所有偶數碰巧被存儲在偶數位置的是你的循環跳過。

注意:一個更好的解決方案是完全放棄中間循環,並在打印時進行分割。

2

您的第二個for循環的正文i。由於它在循環的子句中也是先進的,所以它先行兩次,有效地跳過任何其他元素。刪除這些進步,並且你應該確定:

for(int i=0; i<10; i++) { 
    if (a[i] % 2 == 0) { 
     a[i] /= 2; 
    } 
} 
+1

感謝球員,希望我會變得更好,並幫助社區,而不是像這樣愚蠢的問題。但再次感謝您向我解釋的速度和清晰程度。祝你有個美好的一天:) –

0

在你的程序中,增加循環,循環中的for循環變量i的兩倍還增加值一次這樣的值被跳過那就是你的理由越來越錯output.herewith我重視的修正程序及其output.hope你理解這個概念。謝謝

#include <stdio.h> 
int main(void) 
{ 
    int a[10]; 
    printf("\n Given Values are"); 
    printf("\n-----------------"); 

    for(int i = 0; i < 10; i++) 
     scanf("%d", &a[i]); 

    for (int i = 0; i < 10; i++) 
    { 
     if (a[i] % 2 == 0) 
      { 
      a[i] = a[i]/2; 

      } 
     } 
    printf("\n After dividing the even numbers by 2 and print in reverse order"); 
    printf("\n ----------------------------------------------------------------\n"); 
    for(int i = 9; i > 0; i--) 
    printf("%d\n", a[i]); 
return 0; 
} 

輸出

Given Values are                                            
-----------------                                            
1                                                
2                                                
3                                                
4                                                
5                                                
6                                                
7  
8                                                
9                                                
10                                               

After dividing the even numbers by 2 and print in reverse order                                
---------------------------------------------------------------- 
5                               
9                                                
4                                                
7  
3                                                
5                                                
2                                                
3                                                
1                                                
相關問題