在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;
}
答案 0 :(得分:1)
}
。semicolon ;
。C89
中不起作用。如果需要分配在编译时不知道其大小的数组,这意味着您仅在运行时使用malloc()
时知道该大小。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;
}