0

我正在为一个程序编写一个函数,该程序要求用户输入一个“学生证号码”并将其存储在数组中。在存储函数之前,必须检查数组中是否还没有该数字,因为学生编号必须是唯一的。它还包括一个指向 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;}
4

2 回答 2

0

因此,我看到的主要内容是,在您扫描数字之后,您实际上并没有检查该数字是否已经在数组中。您只是检查它是否在特定索引处。

更具体地说,您需要的不仅仅是 for 循环中的 if 语句;也许是另一个循环查看到目前为止已使用的索引。

编辑:最大的问题是在 else 子句中,不要增加i. 其次,您需要一些金丝雀变量来让您知道您是否已对 printf 进行了调用。

例如,这是我对这些循环的想法:

for (h = 0; h < *pum; h++) {
    printf(">>>Student ID:");
    scanf("%d", &temp);

    canary = 0; // assuming you initialize this at beginning of function
    for (i = 0; i < *pnum; i++) {
        if (temp == a[i]) {
            printf("ERROR:%d has already been used!\n",temp);
            canary = 1;
            break;
        }
        // DON'T INCREMENT i, LOOP IS ALREADY DOING IT
    }

    // if canary is still 0, we know we haven't called that printf
    // and can add in the element. Only then do we increment the count.
    if (canary == 0) {
        a[*pnum] = temp;
        (*pnum)++;
    }
}
于 2012-08-07T17:56:08.137 回答
0

如果 - 如果 - 您可以按排序顺序维护您的 ID,那么您可以获得许多重大优化。这几乎肯定会涉及远离作为容器的简单数组。像堆这样的东西会很合适。如果您想继续使用数组并且不介意插入是 O(n),那么您可以保持排序顺序并使用二进制搜索进行存在性检查。不幸的是,标准库bsearch()函数没有告诉你应该在哪里如果找不到匹配项,则插入一个元素。编写你自己的二分搜索是一件非常困难的事情,但如果你这样做,它是很好的可重用代码。您想要的是一个函数,如果元素存在则返回 true 或 false,并且如果它不存在则返回匹配元素的指针或立即较低的值(或者如果没有元素更小,则返回数组指针本身。)然后在如果找不到匹配项,您会将所有较大的元素移到一个位置并插入新元素。

由于这是一个家庭作业问题,我猜您仅限于 C,但是 C++ STLset<int>将您必须做的工作减少到几行。

于 2012-08-07T20:09:59.257 回答