以下是我在编写程序时遇到的问题,我提示用户输入尽可能多的值,然后我打印出这样输入的每个整数的结果.
我建议在我的上一个问题如何针对输入测试用例文件测试我的程序时使用/sf/users/22387711/进行动态记忆分配 .
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*start;
void insertatend(int d)
{
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
n->data=d;
n->next=NULL;
if(start==NULL)
{
start=n;
}
else
{
struct node *tmp;
for(tmp=start;tmp->next!=NULL;tmp=tmp->next);
tmp->next=n;
}
}
int max(int a,int b)
{
int c=(a>b)?a:b;
return c;
}
int maxCoins(int n)
{
int arr[n+1],i;
arr[0]=0;
arr[1]=1;
arr[2]=2;
arr[3]=3;
if(n>2)
{
for(i=3;i<=n;i++)
{
int k= arr[(int)(i/2)]+arr[(int)(i/3)]+arr[(int)(i/4)];
arr[i]=max(i,k);
}
}
return arr[n];
}
int main(void)
{
int coins,i;
start=NULL;
struct node*p;
while(scanf("%d",&coins))
{
insertatend(coins);
}
for(p=start;p!=NULL;p=p->next)
{
printf("%d\n",p->data);
}
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序成功运行.我能够提供任意数量的输入,如果我尝试通过按CTRL + Z来突破,程序不会响应.我不能为这些问题使用动态内存分配吗?如果是的话,我错在哪里?
while(scanf("%d",&coins))
Run Code Online (Sandbox Code Playgroud)
如果将CTRL + Z发送到程序,则scanf返回EOF,这是一个负数而不是0,因此contition的计算结果为true,并且您处于无限循环中.测试
while(scanf("%d",&coins) > 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |