【问题标题】:How to use a linked List to store two real numbers in one node如何使用链表在一个节点中存储两个实数
【发布时间】:2016-08-06 21:06:26
【问题描述】:

我创建了 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("%.2f\n", curr->val);
      total_y   = total_y + curr->val;
      ysq       = curr->val;
      total_ysq = total_ysq + (ysq * ysq);
      curr      = curr->next;
    }
    else
    {
      printf("%.2f\n", 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: %.3f\n", avg_x);
  printf("Y : %.3f\n\n", avg_y);

  fclose(pointer);
  return 0;

} //End of Main

dummy.txt:

130 650 99 150 128 302 95 945 368 961 186 699 132 272 291 331 199 1890 788 1601

【问题讨论】:

    标签: c linked-list singly-linked-list


    【解决方案1】:

    只需在你的 struct list_el 上添加一个浮点数

    struct list_el
    {
      float val1;
      float val2;
      struct list_el * next;
    };
    

    【讨论】:

      【解决方案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;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-01
        • 2012-10-14
        • 1970-01-01
        • 2013-04-14
        • 2011-11-04
        • 1970-01-01
        • 2016-03-19
        • 1970-01-01
        相关资源
        最近更新 更多