構造体の配列を生成するコードをいくつか書きました。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;
}