【问题标题】:Do loop to generate array of unique random array循环生成唯一随机数组的数组
【发布时间】:2013-01-13 02:43:19
【问题描述】:

我编写了一些代码来生成结构数组。 id 变量旨在是唯一的并随机生成。但是,似乎正在发生的事情是,如果生成函数(生成并填充结构数组)在数组中遇到匹配的数字,则标志变量设置为 0,并且它退出 do 循环而不创建新的随机数重新检查匹配。然后当循环退出时,代码继续并将匹配的随机数分配给数组中的空白点。作为一个警告,我意识到只取所有 10 个可能的整数,移动它们并填充数组会更简单,但我试图使用一个小样本来掌握 rand() 的窍门,这样我就可以看到它是什么在调试器中做。我怀疑我只是盯着这个太久了,尝试了太多东西,但任何建议都会受到赞赏。谢谢。

编辑:只是为了澄清我的问题特别涉及 do 循环以及我需要做些什么来确保找到匹配项时,程序会生成一个新的随机数并再次开始搜索匹配项。这应该对数组中的每个位置重复,直到每个 id 元素都是唯一的。目前,当我运行程序时,我仍然得到重复的数字。

#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
#include<assert.h>

struct student{
    int id;
    int score;
};

struct student* allocate(){
     /*Allocate memory for ten students*/
    struct student* s = malloc(10 * sizeof(struct student));
    assert (s != 0);

     /*return the pointer*/
     return s;
}

void generate(struct student* students){
     /*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
   int i, j;
   int flag;
   int randNum = 0;
   for (i = 0; i < 10; i++) {
        flag = 1;
         do {
            randNum = (rand()%10 + 1);  //generate random ID for each student

            for (j = 0; j < 10 && flag == 1; j++) {  //search array for matching numbers
                if (students[j].id == randNum) {
                    flag = 0;
                }
                if (j == 9 && flag == 1) {
                    flag = 0;
                }
            }
         }
        while (flag == 1);  //set condition

        students[i].id = randNum;
        students[i].score = (rand()%(100 - 0 + 1) + 0);  //generate random score for each student
    }
}


void output(struct student* students){
     /*Output information about the ten students in the format:
              ID1 Score1
              ID2 score2
              ID3 score3
              ...
              ID10 score10*/
        int i;
        printf("Student scores: \n\n");
        for (i = 0; i < 10; i++) {
            printf("\t%d, %d\n", students[i].id, students[i].score);
        }
}

void summary(struct student* students){
     /*Compute and print the minimum, maximum and average scores of the ten students*/
    int sumS, minS, maxS, avgS, i, j, tempID, tempS;
    printf("Sorted students by scores: \n");
    for (i = 0; i < 10; i++) {
        sumS += students[i].score;
        for (j = 0; j <10; j++) {
            if (students[i].score < students[j].score) {
                tempS = students[j].score;
                tempID = students[j].id;
                students[j].score = students[i].score;
                students[j].id = students[i].id;
                students[i].score = tempS;
                students[i].id = tempID;
            }
        }
    }
    for (i = 0; i < 10; i++) {
        printf("\t%d, %d\n", students[i].id, students[i].score);
    }
    printf("Minimum score: %d\n", minS = students[0].score);
    printf("Maximum score: %d\n", maxS = students[9].score);
    printf("Average score: %d", avgS = sumS/10);
}

void deallocate(struct student* stud){
     /*Deallocate memory from stud*/
     free(stud);
}

int main(){
    struct student* stud = NULL;

    /*call allocate*/
    stud = allocate();

    /*call generate*/
    generate(stud);

    /*call output*/
    output(stud);

    /*call summary*/
    summary(stud);

    /*call deallocate*/
    deallocate(stud);

    return 0;
}

【问题讨论】:

    标签: c random do-loops


    【解决方案1】:

    如果已经选择了数字,则将标志设置为0,因此您应该测试while(flag == 0),并在循环开始时将标志重新设置为1

    do {
        flag = 1;
        randNum = (rand()%10 + 1);  //generate random ID for each student
    
        for (j = 0; j < i && flag == 1; j++) {  //search array for matching numbers
            if (students[j].id == randNum) {
                flag = 0;
            }
        }
    }
    while (flag == 0);  //set condition
    

    现在,flag == 0 的意思是“已经看过,再试一次”,flag == 1 的意思是“这是一个新数字,继续往数组中写入”。

    此外,您只填充了索引&lt; i 的数组槽,因此比较循环不应转到9,而应仅转到i-1

    【讨论】:

    • 我尝试了移动语句“flag = 1;”的解决方案在do循环的括号内并将条件更改为“flag == 0”,但结果是无限循环。
    • @user1852050 当达到9 时,我最初忘记删除flag0 的错误设置。现在已修复,请重试。
    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2010-12-09
    • 1970-01-01
    • 2012-03-14
    • 2012-06-05
    相关资源
    最近更新 更多