42(去掉陣列中的重複數字,只輸出一個相同數字)
阿新 • • 發佈:2021-03-23
42 date:2021.3.21
要點:
calloc 用於分配記憶體空間,形式: (型別說明符)calloc(n,size)
在記憶體動態儲存區中分配n塊長度為"size"位元組的連續區域,函式的返回值為該區域的首地址
(型別說明符*)用於強制型別轉換。
calloc函式與malloc函式的區別在於calloc函式一次可以分配n塊區域
詳細程式碼如下:
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#define N 10
typedef struct ss
{ char num[10];
int s;
} STU;
STU *fun(STU a[], int m)
{ STU b[N],*t;
int i, j,k;
/*************found**************/
t=(STU*)calloc(m,sizeof(STU));
for(i=0;i<N;i++) b[i]=a[i];
for(k=0;k<m;k++)
{ for (i=j=0;i<N;i++)
if (b[i].s>b[j].s) j=i;
/*************found**************/
strcpy(t[k].num,b[j].num); //因為num是陣列型別,所以不可以直接用t[k].num = b[j].num這種賦值辦法
t[k].s=b[j].s;
b[j].s=0;
}
return t;
}
void outresult(STU a[],FILE *pf)
{ int i;
for(i=0;i<N;i++)
fprintf(pf, "No=%s Mark=%d\n ",
a[i] .num, a[i].s);
fprintf(pf, "\n\n ");
}
void main()
{ STU a[N]={{ "A01 ",81},{ "A02 ",89},{ "A03 ",66},{ "A04 ",87},{ "A05 ",77},
{ "A06 ",90},{ "A07 ",79},{ "A08 ",61},{ "A09 ",80},{ "A10 ",71}};
STU *pOrder;
int i, m;
system("CLS");
printf("*****THE RESULT*****\n");
outresult(a,stdout);
printf("\nGive the number of the students who have better score: ");
scanf("%d",&m);
while(m>10)
{ printf("\nGive the number of the students who have better score: ");
scanf("%d",&m);
}
pOrder=fun(a,m);
printf("***** THE RESULT*****\n");
printf("The top :\n");
for(i=0;i<m;i++)
printf("%s %d\n",pOrder[i].num, pOrder[i].s);
free(pOrder);
}
要點:
注意下標
詳細程式碼如下:
#include <stdio.h>
#define N 80
int fun(int a[], int n)
{
/*
analyse:
*/
int i , j = 1;
for(i = 1; i<n; i++)
{
if(a[i] != a[i-1]) //若該數與前一個數不相同,則要保留
a[j++] = a[i];
}
return j; //返回不相同的個數
/*
int i,j=0;
for(i = 0; i<20; i++)
{
if(a[i] == a[i+1])
a[j] =a[i];
}
*/
}
void main()
{
FILE *wf;
int a[N]={ 2,2,2,3,4,4,5,6,6,6,6,7,7,8,9,9,10,10,10,10}, i, n=20;
printf("The original data :\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
n=fun(a,n);
printf("\n\nThe data after deleted :\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n\n");
/******************************/
wf=fopen("out.dat","w");
for(i=0; i<n; i++)
fprintf(wf,"%3d",a[i]);
fclose(wf);
/*****************************/
}