2013-03-31 54 views
3

任何幫助將非常讚賞我遇到的這個問題。 我試圖創建一個循環來查找主對角線值都大於或等於7的30x30陣列。 數組中填充了隨機整數。C編程陣列循環

我的問題是循環本身,我似乎無法弄清楚如何創建如此大的系列循環..讓我瘋狂!

當我設法創建一個滿足條件的數組時,我需要顯示它所花費的嘗試次數。如果嘗試超過100萬次,程序應該簡單地「放棄」,表明這是不可能的。

這是我設法到目前爲止(不是整個代碼,只是我需要幫助的位),但是輸出完全沒有。 我保證我甚至沒有接近正確的解決方案......但我會感激一個點在正確的方向!

感謝提前:)

count=0; 

for(a=0;a<30;++a) 
for(b=0;b<30;++b) 
    random2[a][b]=rand()%10; 

while(count<=1000000) 
{ 
for(a=0;a<30;++a) 
{ 
    if(random2[a][a]>=7) 
    {  
     ++a; 
     if(a==30&&random2[a][a]>=7) 
      printf("%d", count); 
    } 
     else 
     { 
      ++count; 
      for(a=0;a<30;++a) 
       for(b=0;b<30;++b) 
        random2[a][b]=rand()%10; 
     } 
} 
} 

printf("%d", count);      

回答

1

你已經在你的循環做了一些奇怪的事情。簡單的修復方法是刪除其中一個++a(我建議第二個),並在012中去除break

更好的解決方法是按照您的意思編碼。最低限度地改變你的例子:

int count,a,b; 
for(count = 0; count<=1000000; ++ count) { 
    for(a=0;a<30;++a) 
     for(b=0;b<30;++b) 
      random2[a][b]=rand()%10; 
    for(a=0;a<30;++a) 
    { 
     if(random2[a][a]>=7) 
     { 
      if(a==30&&random2[a][a]>=7) 
      printf("%d", count); 
     } 
     else 
     { 
      break; 
     } 
    } 
    if(a == 30) { 
     break; 
    } 
} 

一個更好的解決辦法是計算你的陣列算法,而不是依靠隨機的機會給你一個好的結果。例如,將您的對角線設置爲隨機7,8或9(這會給出相同的最終結果和概率)。

1

我想既然你說的數組是30X30存在行

if(a==30&&random2[a][a]>=7) 

一個問題,指數的最大值爲29x29。所以random2[30][30]不存在。至於代碼,嘗試

while(count<=1000000) 
{ 
    for(a=0;a<30;a++) 
    { 
    for(b=0;b<30;b++) 
    { 
     random2[a][b]=rand()%10; 
     if(a==b) 
     { 
      while(random2[a][a]<7) 
      { 
        ++count; 
        random2[a][b]=rand()%10; 
      } 
     } 
    } 
    } 
} 

如果你想計數的值要少,使用這種會給你你需要

陣列,

if(random2[a][a]<7) 
{ 
    random2[a][a]=(rand()+7)%10 
} 
+0

這似乎工作的大部分,非常感謝。然而,我看起來作爲輸出的價值總是在1000000和1001000之間,這看起來很奇怪。 :P – user2229471

1

你混合內for循環計數器'a'與值計數器(在您的程序中也是'a')。嘗試這樣的:

int found = 0; 
for (count = 1; count <= 1000000 && !found; count++) { 
    // (re)fill the array with random numbers 
    for (a = 0; a < 30; a++) for (b = 0; b < 30; b++) random2[a][b] = rand() % 10; 
    // now check the array 
    found = 1; // assume all values are >= 7 
    for (a = 0; a < 30; a++) 
    if (random2[a][a] < 7) { // found a bad value 
     found = 0; 
     break; 
    } 
}