2016-07-11 166 views
0

我是C新手,寫了一段代碼,我想顯示「?」在它與數組中的值匹配的屏幕上。如果我有一個用index_location [6] = {0,1,5,8,9,12}初始化的數組;我的預期產出如下。任何幫助或幫助,以幫助我是不勝感激。代碼不能正確顯示輸出

輸出: ?? @@@?@@ ?? @@?

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

// 
int main(void) 
{ 
    int index_location[6] = {0, 1, 5, 8, 9, 12}; 
    int len=sizeof(index_location)/sizeof(int); 

    for (int a = 0; a < len; a++) 
    { 
     for(int b = 0; b < len; b++) 
     { 
      if (a == index_location[b]) 
      { 
       printf("%c",'?'); 
      } else { 
       printf("%c",'@'); 
      } 
     } 
    } 
    printf("\n"); 
} 
+1

你真的應該表現出你真正得到的。我懷疑這是比預期的輸出更多的數據。你確定需要雙循環嗎?我認爲你應該使用一個循環。在C中,你需要使用'for(int a = 0; a

+0

根據您的要求,它不應該是printf('?') –

+0

數組邊界是關閉的for(a = 0; a evaitl

回答

3

你只需要一個循環。您需要檢查索引位置0..12(其中12是index_location陣列中的最後一個條目),檢查是否需要每次打印?@。當您打印對應於index_location條目之一的字符時,您需要繼續查看下一個條目。你可以添加一個自由的調用集合來確保事物受到控制,但只要數組按照排序順序排列,就應該沒問題(即使不是這樣,你也可能會放棄它,儘管你可能會錯過一些要求?分)。

#include <stdio.h> 

int main(void) 
{ 
    int index_location[6] = {0, 1, 5, 8, 9, 12}; 
    int len = sizeof(index_location)/sizeof(index_location[0]); 
    int max = index_location[len - 1]; 
    int idx = 0; 

    for (int a = 0; a <= max; a++) 
    { 
     if (a < index_location[idx]) 
      putchar('@'); 
     else 
     { 
      putchar('?'); 
      idx++; 
     } 
    } 
    putchar('\n'); 
    return 0; 
} 

輸出:

[email protected]@@[email protected]@[email protected]@? 
+0

感謝您的解釋。 – user3221699

0

的錯誤就在於你的for循環。我會用下面的解決方案。
如果陣列index_location []是按升序排序,雙初始化這一翻譯用這個循環:

int max = index_location[len-1]; 
for(int i = 0,j = 0; i <= max; i++) 
{ 
    if (i == index_location[j]) 
    { 
     printf("%c",'?'); 
     j++; 
    } 
    else { 
     printf("%c",'@'); 
    } 
}