【问题标题】:array element is not printing数组元素未打印
【发布时间】:2020-07-04 10:22:23
【问题描述】:

在 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;
}

【问题讨论】:

  • 您注意到第二行for(..); 后面的分号了吗?你的编译器不会抛出任何警告(关于“gaurds”)吗?
  • 请注意fflush(stdin); 什么都不做。还要刷新输出并写入换行符 (\n) 怎么样?
  • 请在发布前正确缩进您的代码。
  • 投票关闭错字(@kabanus 解释)
  • 你的 for 需要一个右大括号 }

标签: arrays c printf


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

【讨论】:

  • 感谢您的帮助
  • @Ayu91-我的荣幸。 :-)
猜你喜欢
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
相关资源
最近更新 更多