2016-02-08 33 views
-1

(這是什麼意思)在C的數字檢查

在處理「交易或不交易」項目時,我做了一個函數check(); 檢查是否有任何兩個案例是相同的,如果它們是,更改其中一個,然後再次檢查它。

函數處理爲獎品的情況設置隨機數,然後調用check();

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

void deal(void); 
void check(void); 


int cases[22]; 
int prizes[22]=1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250}; 



int main() 
{ int a=0; 
deal(); 
while (a<22){ 
    printf("%d \n",cases[a]); 
a++; 
} 

return 0; 
} 

void deal(void){ 


srand(time(NULL)); 
int r; 
int n = 1; 

while (n <= 22){ 
    r = rand() % 21; 
    cases[n] = prizes[r]; 
    n++; 

}//Ends while loop 

check(); 


}//Ends function 

void check(void){ 
int i = rand() % 21; 
int m = 0; 
int n = 0; 

srand(time(NULL)); 

while(m < 22){//Nested while loop 

    while (n < 22){ 
     if (m == n){ 
      n++; 
      continue; 
     } else { 
     if(cases[m] == cases[n]){ 

      cases[m] = prizes[i]; 
      i = rand() % 21; 
      continue; 
     }else{ 

     n++; 
     continue; 

     } 

     } 

    }//End of inside loop 
m++; 
n = 0; 
}//End of nested loop 


}//End function 

然而,它打印出數字未選中,或未正確檢查。 我正在使用代碼塊IDE

在此先感謝。

+2

你的問題是什麼? – Wossname

+0

如何使用每個打印出來。 – Bonediggerninja

+1

'while(n <= 22)'當'n'爲22時會導致溢出。因爲22不是'cases'和'prizes'的有效索引。另外,請格式化您的代碼,以使其可讀。其實,那真的是你的代碼嗎?它不應該編譯爲'獎品'具有不匹配大括號的初始化程序。 – kaylum

回答

1

你幾乎在那裏,有一個簡單的(很常見的)算法或者在數組上進行爭奪。通過陣列一次,您可以隨機分配每個值的位置而不重複它們。由於加擾功能的操作,現在不需要檢查功能。

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

void deal(void); 
void check(void); 

int cases[22]; 
int prizes[22] = {1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250}; 

int main() 
{ 
    srand(time(NULL)); 

    int a = 0; 
    deal(); 

    for(a = 0 ; a < 22 ; a++) 
    printf("%d \n", cases[a]); 

    return 0; 
} 

//this is a neat algorithm for re-ordering an array without duplication 
void scramble(int* array, int length) 
{ 
    int i; 
    int r; 
    int temp; 

    for(i = 0 ; i < length ; i++) 
    { 
    //swap this element with a random one to it's left (or itself) 
    r = rand() % (i + 1); 

    temp = array[r]; 
    array[r] = array[i]; 
    array[i] = temp; 
    } 
} 

void deal(void) 
{ 
    int r; 
    int n = 1; 

    //copy the prizes across directly 
    for(n = 0 ; n < 22 ; n++) 
    cases[n] = prizes[n]; 

    scramble(cases, 22); 
} 

仔細檢查scramble()函數,你會發現它很有趣。

根據評論中的建議編輯將算法更改爲單次通過。

+4

他的錯誤在哪裏?你的答案如何解決?我看到的只是一個全新的程序,而不是他的解決方案的簡單修復。對於他的學習,指出錯誤,只有修復纔會更好。 –

+1

這是一個非常糟糕的方式來給出答案。我同意@PaulOgilvie,你應該解釋你寫的是什麼。 -1 –

+0

有時我希望SO有一個「另存爲草稿」按鈕。對半職員抱歉。 – Wossname