c - 如何在不要求用户输入的情况下找到一个数字的出现频率?

标签 c arrays

我正在尝试编写一个程序来查找数字的频率,而不要求用户输入。要明确的是,我正在寻找一种想法,用户无需输入他需要计算的值频率,编译器应该默认告诉列表中每个数字的频率,而不是用户给出一个数字。下面提到的是我的代码。

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

float frequency (int theArray [ ], int number, int x)
 {
int count = 0;
float mount=0.0;
float tot = (float)number;
int u;
int k;
float q,h;

   //   printf("%d",number);

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

for(k = 0; k< number; k++)
{
    if(theArray[k]==x)

           //count(theArray[k])         
    {       mount++;

    }
  }
  if(mount>1)
    {


    q = mount/tot;


    return q;

    }
   else
  {


   h = mount/tot;

    return h;
    }
  } 


 void main()
   {
   FILE*file = fopen("num.txt","r");
   int integers[100];
   int theArray[100];
   int i=0;
   float e;
   int num;
   int x,k;
   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*/
 e =  frequency(integers,i,x); 
printf("\n probability of %d is %f",x,e);
getch();
fclose(file);
     }

所以我现在的输出是: 1) 号码列表 2)数字出现的频率 3)我的号码的概率 相反,我正在寻找能够给出我的号码的概率和频率的东西,而不需要任何
用户输入。即我正在寻找类似的东西

输出: 这个数字出现的频率是----,它的概率是--------

任何帮助将不胜感激。

最佳答案

这个循环将为你解决问题

for(i = 0; i < number; i++)
{
    if(array[i] == -999) // checking if the number has been counted before or not
        continue;
    temp = array[i]; // take each number from the array one by one
    for(j = 0; j < number; j++) // iterate over the array to check the number of occurences of temp
    {
        if(array[j] == temp) 
        {
            array[j] = -999; // putting -999 at places where the number has already been counted
            count++;
        }
    }
    printf("frequency of %d is %d, and probability is %f", temp, count, count/number);
    count = 0;
}

关于c - 如何在不要求用户输入的情况下找到一个数字的出现频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961577/

相关文章:

javascript - XML 请求的多数组

c - 从数组和程序中提取整数值而不显示 printf 函数

c - 在 main 之前初始化自定义输出流

javascript - 延迟显示 forEach 循环中的数组元素

php - php foreach循环中的HTML表,其中仅当元素等于表列标题名称时才填充单元格数据

c - 使用结构体和数组

c - 查找数组中的重复项

c - 将值传递给 C 上的 typedef 结构

c - 线程局部变量和内联汇编

c - 将数组中的给定句子与单独数组中的单词分开