程序填空答案(每空2分)
1.输入一行字符,以回车结束输入,将其中的数字进行累加并计算平均值。
#include <stdio.h>
int main()
{
char c;
float sum=0, averg=0;
int digit=0;
printf("请输入一行字符:\n");
while((c=getchar())!=【‘\n’】)
{ if (【c>=’0’&& c<=’9’】)
{ sum = sum+【c-‘0’】;
【digit++】;
}
}
averg = sum/digit;
printf("数字和为:%.0f\n平均值为:%.2f\n", sum, averg);
return 0;
}
2. 先按学号由小到大的顺序从键盘输入学生的学号和成绩,然后从键盘任意输
入一个学生的学号,查找并打印具有该学号的学生的成绩。
#include <stdio.h>
#define ARR_SIZE 40
int main()
{ 【int BinSearch(long a[], int n, long x)】;
float score [ARR_SIZE];
int n, i, pos;
long num[【ARR_SIZE】], x;
printf("Please enter total number:");
scanf("%d", &n);
printf("Please enter the number and score:\n");
for (i=0; i<n; i++) scanf("%ld%f", &num[i], &score[i]);
printf("Please enter the searching number:");
scanf("%ld", &x);
pos = BinSearch( 【score ,n ,x 】 );
if ( 【pos>=0】 ) printf("score = %4.0f\n", score[pos]);
else printf("Not found!\n");
return 0;
}
int BinSearch(long a[], int n, long x)
{
int low=0, high= n - 1, mid;
while (low <= high)
{ mid = (high + low) / 2;
if (x > a[mid]) low = 【mid+1】 ;
else if (x < a[mid]) high = 【mid-1】 ;
else return ( 【mid】 );
}
return(-1);
}
3. 设有一个描述零件加工的数据结构为:零件号;工序号;加工费;指针。
下述程序先动态建立一个包含5个零件加工数据的单向链表;链表建好后删除链表的第3个结点,但要保证链表不断;最后输出该链表数据。
#include
#include
#define LEN sizeof(struct Parts)
struct Parts
{ char no[10];
int 【wnum】;
float cost;
【struct Parts】* next;
};
void main( )
{ struct Parts *head, *p, *p_front;
int i;
head=NULL;
for(i=0;i<5;i++)
{ p=(【struct Parts *】)malloc(LEN);
scanf("%s%d%f",【&p->no】,&p->wnum,【&p->cost】);
p->next=head;
head=p;
}
for(i=0;i<2;i++)
{ p_front = p;
p=p->【】;
}
【】;
p=【】;
while(p!=NULL)
{ printf("%s, %d, %f\n",【】, p->wnum, p->cost);
p=p->next;
}
}。