簡體   English   中英

在結構類型中填充4變量並使用malloc

[英]Filling 4 variable in a struct type and using malloc

我需要編寫一個簡單的程序,要求用戶在結構變量數據中插入4個雙精度類型變量。

   struct Data  
    {
      double a;
      double b;
      double c;
      double average;
    };
struct Data *ptr_name;
int i;

首先,詢問用戶大小:

 printf("Please enter the size:");
 scanf("%d", &size);

然后,使用malloc。 (我不知道如何使用...)

像這樣... ptr_name = ()malloc();

然后使用for循環從用戶獲取a,b,c。

for(i = 0; i < size; i++)
{
 //dont know how to put the staement..
}

最后,打印出所有內容,包括平均值。

for(i = 0; i < size; i++)
    {
     //same as above...
    }

差不多了,我現在正在學習結構類型和malloc,通過瀏覽Web無法理解...幫助,謝謝。

malloc的調用應為:

ptr_name = malloc (sizeof (struct Data) * size);

以下功能從控制台讀取struct Data實例/向控制台寫入:

static struct Data 
read_from_console ()
{
  struct Data d;

  d.a = 0.0f; d.b = 0.0f; d.c = 0.0f; d.average = 0.0f;
  printf ("Enter values separated by comma: (a, b, c): ");
  fflush (stdout);
  if (scanf ("%lf, %lf, %lf", &d.a, &d.b, &d.c) != 3)
    {
      printf ("Invalid input\n");
      exit (1);
    }
  else
    d.average = (double) ((d.a + d.b + d.c) / 3.0f);
  return d;
}

static void
print_to_console (struct Data* d)
{
  printf ("a=%f, b=%f, c=%f, average=%f\n", d->a, d->b, d->c, d->average);
  fflush (stdout);
}

您可以從main函數內部的循環中調用它們:

int
main ()
{
  struct Data *ptr_name;
  int count;
  int i;

  printf ("Please enter size: ");
  fflush (stdout);
  if (scanf ("%d", &count) != 1)
    {
      printf ("Invalid input\n");
      return 1;
    }
  ptr_name = malloc (sizeof (struct Data) * count);

  for (i = 0; i < count; ++i)
    ptr_name[i] = read_from_console ();

  for (i = 0; i < count; ++i)
    print_to_console (&ptr_name[i]);

  return 0;
}

交互示例:

> Please enter size: 2
> Enter values separated by comma: (a, b, c): 12.00, 12.45, 13.00
> Enter values separated by comma: (a, b, c): 5.4, 5.00, 5.1
a=12.000000, b=12.450000, c=13.000000, average=12.483333
a=5.400000, b=5.000000, c=5.100000, average=5.166667

從...開始

ptr_name = malloc( size * sizeof( *ptr_name ) );

在malloc上查看wikipage

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM