某集合中有3个整数,分别是:128,78和63,从键盘中输入n(n>=1)个整数追加到该集合中。输出追加后该集合中的所有数据,并求该集合中大于平均值元素的个数。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(3 * sizeof(int));
if (p == NULL)
{
printf("Not enough space to allocate!\n");
exit(1);
}
*p = 128;
*(p + 1) = 78;
*(p + 2) = 63;
int n;
printf("Please input the new number of data to be entered:\n");
scanf_s("%d", &n);
int* ptr = (int*)realloc(p, (3 + n) * sizeof(int));
if (ptr == NULL)
{
printf("Not enough space to allocate!\n");
exit(1);
}
int i, sum = 0, cnt = 0;
for (i = 0; i < n; i++)
{
printf("请输入第%d个数:\n", 3 + i + 1);
scanf_s("%d", ptr + 3 + i);
}
for (i = 0; i < 3 + n; i++)
sum += *(ptr + i);
double avg = (double) sum / (4 + n);
for (i = 0; i < 3 + n; i++)
{
printf("%6d", *(ptr + i));
if (*(ptr + i) < avg)
cnt++;
}
printf("\n");
printf("集合中大于平均值元素的个数为:%d.\n", cnt);
free(ptr);
system("pause");
return 0;
}