我正在为一个程序编写一个函数,该程序要求用户输入一个“学生证号码”并将其存储在数组中。在存储函数之前,必须检查数组中是否还没有该数字,因为学生编号必须是唯一的。它还包括一个指向 int 的指针,该指针表示到目前为止已存储了多少学生编号。我已经写了一些代码,但它不工作:( 有人能说明一下吗?这是我的代码:
void update_student_id(int a[], int*pnum)
{
int temp,h;
for (h=0;h<=*pnum;h++){
printf(">>>Student ID:");
scanf("%d",&temp);
if (temp==a[h]){
printf("ERROR:%d has already been used!\n",temp);
h=*pnum+1;
}
else
h=*pnum+1;
}
a[*pnum]=temp;
*pnum++;
好的,带有 2 个 for 循环的新版本,改进但还没有工作:(
void update_student_id(int a[], int*pnum)
{
int temp,h,i;
for (h=0;h<=*pnum;h++){
printf(">>>Student ID:");
scanf("%d",&temp);
for(i=0;i<=*pnum;i++)
if (temp==a[i]){
printf("ERROR:%d has already been used!\n",temp);
i=*pnum+1;
}
else i++;
}
a[*pnum]=temp;
(*pnum)++;
}
在丹尼斯的帮助下解决了问题,最终代码:
void update_student_id(int a[], int*pnum)
{
int temp,h,i,canary;
for (h = 0; h <= *pnum; h++) {
printf(">>>Student ID:");
scanf("%d", &temp);
canary = 0;
for (i = 0; i < *pnum; i++) {
if (temp == a[i]) {
printf("ERROR:%d has already been used!\n",temp);
canary = 1;
break;
}
}
if (canary == 0) {
a[*pnum] = temp;
(*pnum)++;
break;
}
}
return;}