添加数组元素并存储在数组中

时间:2015-06-29 16:48:08

标签: c arrays

这些代码从文件中获取数据并将其存储在数组中。然后它搜索数组,如果数字在.5和50,000之间(只是删除0和大数字),它进入if语句。在此语句中,如果数字等于下一个,它将检查另一个数组以过滤掉小数和大数,然后将其添加并将其存储到平均值并添加计数器。这样做直到array2中的数字不等于它出来的下一个数字并计算它的平均值,等等。

它一切正常,直到它达到平均值[j] = mean [j] + array1 [i],我尝试使用printf检查该部分并且它吐出一个巨大的负数。均值数组与计数器一起设置为全零。 PLZ帮助:L

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

int main(void)
{
  FILE *fp;
  float array1[1000], array2[1000], mean[1000], average[1000], counter[1000], range[1000], upper[1000], lower[1000];
  int a, h, i, r, j = 0, pos, found = 0, extrinsic[1000];
  int b=0;
  int linect = 1;
  char buf[128];
  extrinsic[100] = 0;
  mean[100] = 0;
  counter[100] = 0;
  range[100] = 0;
  upper[100] = 0;
  lower[100] = 0;
  average[100] = 0;
  i = 0;
  j = 0;
  fp = fopen("data.txt", "r");

  if(fp == NULL)
  {
    puts("Cannot open file for reading");
    scanf("%d", &a);
    exit(EXIT_FAILURE);
  }

  while( linect < 1000 ) 
    {
    fgets(buf, sizeof(buf), fp);
    sscanf(buf, "%f", &array1[i]);
    //printf("Set %d - 1st: %f\n", linect, array1[i]);
    linect++;
    i++;
    }
  fclose(fp);


  linect = 0; //reads lot data file and puts it in array2
  i = 0;
  fp = fopen("lot_numbers.txt", "r");
  if(fp == NULL)
  {
    puts("Cannot open file for reading");
    scanf("%d", &a);
    exit(EXIT_FAILURE);
  }
  while( linect < 1000 ) 
    {
    fgets(buf, sizeof(buf), fp);
    sscanf(buf, "%f", &array2[i]);
   // printf("Set %d - 1st: %f\n", linect, array2[i]);
    linect++;
    i++;
    }


  for (i = 0; i < 999; i++) //searches array sets repeated points to zero
  {
      if (array1[i] == array1[i+1])
      {
          array1[i] = 0;
          array2[i] = 0;
      }
  }
  for (i = 0; i < 9; i++)   //searches array
  {
      if (array2[i] > .5 && array2[i] < 50000)
      {
        if (array2[i] == array2[i+1])
        {
          if (array1[i] > .5 && array1[i] < 500){  //ignores zeros and junk data 
          mean[j] = mean[j] + array1[i];
          counter[j]= counter[j] + 1;
        }
      }
      else {
          average[j] = mean[j]/counter[j];
          range[j] = average[j] * 0.1;
          upper[j] = average[j] + range[j];
          lower[j] = average[j] - range[j];
          j++;
           }
      }
  }
  j = 0;
  while (j <10){
  printf("\n%f", mean[j]);
  j++;
  }
scanf("%d", &a);

return 0;
 }

1 个答案:

答案 0 :(得分:0)

我从未在C中看到过这种语法:

表示[100] = 0;

尝试使用标准的init方法 How to initialize all members of an array to the same value?

表示[100] = {0};