Как использовать связанный список для хранения двух вещественных чисел в одном узле
Я создал 20 узлов для хранения 20 элементов, но мне просто нужно 10 узлов, чтобы хранить эти 20 элементов как два элемента в одном узле. Вот мой код
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct list_el
{
  float            val;
  struct list_el * next;
};
typedef struct list_el item;
int main()
{
  item *curr, *head;
  head = NULL;
  FILE * pointer = NULL;
  float  array[20];
  int    j;
  double xsq, ysq, B1, B0, R, rsq, rpart, rdevide, estimate;
  double estimate;
  double total_x   = 0;
  double total_y   = 0;
  double total_xsq = 0;
  double total_ysq = 0;
  double total_xy  = 4303108.0;
  double avg_x     = 0;
  double avg_y     = 0;
  pointer = fopen("dummy.txt", "r");
  //Store the data to a array from the pointer
  for(j = 0; j < 20; j++)
  {
    fscanf(pointer, "%f", &array[j]);
  }
  //make nodes and store data inside the each node head.. in this code segment i want to store two elements in one node
  for(j = 0; j < 20; j++)
  {
    curr       = (item *)malloc(sizeof(item));
    curr->val  = array[j];
    curr->next = head;
    head       = curr;
  }
  curr = head;
  for(j = 0; j < 20; j++)
  {
    if(j < 10)
    {
      printf("%.2fn", curr->val);
      total_y   = total_y + curr->val;
      ysq       = curr->val;
      total_ysq = total_ysq + (ysq * ysq);
      curr      = curr->next;
    }
    else
    {
      printf("%.2fn", curr->val);
      total_x   = total_x + curr->val;
      xsq       = curr->val;
      total_xsq = total_xsq + (xsq * xsq);
      curr      = curr->next;
    }
  }
  //calculate the average of data
  avg_x = total_x / 10.0;
  avg_y = total_y / 10.0;
  printf("Average n");
  printf("X: %.3fn", avg_x);
  printf("Y : %.3fnn", avg_y);
  fclose(pointer);
  return 0;
} //End of Main
Манекен.txt:
130 650 99 150 128 302 95 945 368 961 186 699 132 272 291 331 199 1890 788 1601
2 ответа:
Я создал 20 узлов для хранения 20 элементов, но мне просто нужно 10 узлов, чтобы хранить эти 20 элементов как два элемента в одном узле.Существует два способа добиться этого.
Первый Способ
struct list_el { float val1; float val2; struct list_el * next; };Другой Способ
#define NUM_VALS 2 struct list_el { float val[NUM_VALS]; struct list_el * next; };