数组元素未打印

时间:2020-07-04 10:22:23

标签: arrays c printf

在printf(“%d”,cost [i])下面的代码中,为什么打印垃圾值? 而当我使用printf(“%d”,cost [0]);然后打印正确的答案

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

int main()

{


  int chef = 0,n,i=0;
  scanf("%d",&n);

 int cost[n];
  for(i=0;i<n;i++)
  {   fflush(stdin);
      scanf("%d",&cost[i]);

  }
  for(i=0;i<n;i++);
  {
      if(cost[i]-5>=chef)
      {
          printf(" %d",cost[i]);
          chef=chef+cost[i];
          chef=chef-(cost[i]-5);
      }
 
  return 0;
}

1 个答案:

答案 0 :(得分:1)

  1. 在第二个for循环中缺少关闭}
  2. 在第二个for循环结束时删除semicolon ;
  3. 此代码在C89中不起作用。如果需要分配在编译时不知道其大小的数组,这意味着您仅在运行时使用malloc()时知道该大小。
  4. 按照C标准冲洗标准输入fflush(stdin),这是未定义的行为。但是一些编译器允许它。如果要编写可移植的代码,请不要使用它。

见下文:

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

int main()
{
    int chef = 0, n, i=0, *cost=NULL;
    
    scanf("%d",&n);
    cost = (int*)malloc(n*sizeof(int));
    if(!cost)
    {
        /*malloc failed*/
        puts("malloc failed");
        abort();
    }
  
    for(i = 0; i < n; ++i)
    {   
        scanf("%d",&cost[i]);
    }
 
    for(i = 0; i < n; ++i)
    {
        if(cost[i]-5 >= chef)
        {
            printf(" %d",cost[i]);
            chef=chef+cost[i];
            chef=chef-(cost[i]-5);
        }
    }

    return 0;
}
相关问题