2014-09-21 155 views
0

我在計算文件的大小。我遵循的過程是讀取文件並將其存儲在數組中並計算其大小。然而,我真的不知道......我嘗試了n種方法......我將這個大小作爲屬性傳遞給頻率函數,並與數組的名稱一起使用。計算陣列的大小

#include <stdio.h> 
#include<conio.h> 

void frequency (int theArray [ ], int ??????, int x) 
{ 
    int count = 0; 
    int u; 

    for (u = 0; u < ??????; u++) 
    { 
     if (theArray[u]==x) 
     { 
      count = count + 1 ; 
      /*printf("\n%d",theArray[u]);*/ 
     }  
     else 
     { 
      count = count ; 
     } 
    } 
    printf ("\nThe frequency of %d in your array is %d ",x,count); 
} 

void main() 
{ 
    FILE*file = fopen("num.txt","r"); 
    int integers[100]; 
    int i=0; 
    int r = 0; 
    int num; 
    int theArray[100]; 
    int there[100]; 
    int n; 
    int g; 
    int x; 
    while(fscanf(file,"%d",&num)>0) 
    { 
     integers[i]=num; 
     printf("\n%d",(integers[i])); 
     there[r] = integers[i]; 
     i++; 
    } 
    //printf("%d",there[r]); 

    //printf("\n%d",file); 

    //fclose(file); 

    printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? "); 
    scanf("\n%d", &x);/*Stores Number To Search For Frequency*/ 
    frequency(integers,????????,x); 

    getch(); 
    fclose(file); 
} 

??????是從哪裏讀取文件並存儲它的整數數組的大小。

我無法找到一種方法來計算我複製我的文件的數組的大小。我的想法是計算該文件中一個數字的頻率並計算它出現的概率,從而計算出熵。建議請!

+0

我不知道是否有任何函數來計算數組的長度,但您可以初始化所有元素爲-1,然後複製所有數據,最後檢查直到-1。而且對於良好的編碼,你需要分開跟蹤每個角色,以便它必須明確。 – Avinash 2014-09-21 05:28:57

+0

檢查這個http://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c – nem035 2014-09-21 05:31:28

+1

調用頻率(整數,我,x);' – BLUEPIXY 2014-09-21 05:40:47

回答

0

我不知道你爲什麼要初始化如此多的變量,其中一些像??????這樣的尷尬名字。

你的主要問題是,調用function應該

frequency(integers, i, x); 

你去掉尷尬無關的部分代碼如下

#include <stdio.h> 
#include<conio.h> 

void frequency (int theArray [ ], int number, int x) 
{ 
    int count = 0; 
    int u; 

    for (u = 0; u < number; u++) 
    { 
     if (theArray[u]==x) 
      count++; 
    } 
    printf ("\nThe frequency of %d in your array is %d ",x,count); 
} 

void main() 
{ 
    FILE*file = fopen("num.txt","r"); 
    int integers[100]; 
    int i=0; 
    int num; 
    int x; 
    while(fscanf(file,"%d",&num)>0) 
    { 
     integers[i]=num; 
     printf("\n%d",integers[i]); 
     i++; 
    } 

    printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? "); 
    scanf(" %d", &x);/*Stores Number To Search For Frequency*/ 
    frequency(integers,i,x); 

    getch(); 
    fclose(file); 
} 
0

這段代碼有很多部分沒有意義,但我認爲這是您的調試,試圖找出錯誤。您的具體問題的答案是:

對於從文件中讀取的每個值,您將整數[i]設置爲該值,然後遞增i。因此,我是整數項目的計數。然後你將整數傳遞給frequency(),所以我應該將其作爲count傳遞給第二個參數。

請注意,如果文件中有超過100個值,則會覆蓋索引整數並導致不可預知的行爲。

0

要計算數組的長度:

int len= sizeof(arr)/sizeof(arr[0]); 

它會給沒有循環的數組的長度。