的陣列我已經寫了一些代碼來生成結構的數組。 id變量旨在是唯一的並隨機生成。然而,似乎是發生的是,如果生成函數(其中gnerates和填充結構的數組)數組中遇到的匹配數量,標誌變量設置爲0,並退出do循環不創建一個新的隨機數重新檢查一場比賽。然後,當循環退出時,代碼繼續,並將匹配的隨機數分配給數組中的空白點。作爲一個警告,我意識到這將是簡單的只是把所有10個可能的整數,移動他們,並填補了數組,但我想用一個小樣本,所以我可以看它的獲得)蘭特的竅門(在調試器中執行。我懷疑我只是盯着這太久,嘗試了太多的東西,但任何建議,將不勝感激。謝謝。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;
}
問題是什麼? –