2017-01-23 46 views
0

這是我第一次爲C編寫任務,我對如何實現隨機數字感到困惑。在我的程序中,我已經創建了一個結構化學生,並創建了一個包含10名學生的數組。現在我必須爲這10名學生生成隨機ID號碼和考試成績,但我的老師從來不清楚如何確切地做到這一點。我也不允許更改變量或函數聲明。這是我到目前爲止的代碼:如何爲10個學生的結構生成隨機ID和測試分數

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

struct student { 
    int id; 
    int score; 
}; 

struct student *allocate() { 
    return calloc(sizeof(struct student), 10); 
} 

void generate(struct student* students){ 
    /* 
     *Generate random ID and scores for 10 students, ID being between 0 and 
     * scores equal to (id* 10 % 50) 
     */ 
} 
int main() { 
    struct student *stud = allocate(); 
    generate(stud); 

    return 0; 
} 

他還給出了這樣的指令: 「寫一個函數void generate(struct student* students)用於填充ID和得分的10名學生作爲參數傳遞的數組的領域每個學生都應該有一個ID這與他們在數組中的索引相對應(即數組中的第一個學生應該有id 0),如果每個學生的id是x,則學生的分數應該是(10 * x) % 50

+2

在指令中它說「隨機」? 「對應於它們在數組中的索引的ID」不是隨機的,並且「得分應該是(10 * x)%50」。 – kaylum

+2

該指令不會說「隨機數字」。它具體說數字將基於數組中的索引。 –

+0

看到這也讓我感到困惑,就像他在給學生髮表的評論中說的那樣,它隨機地說,但實際的指令不是 – McGradyMan

回答

1

請嘗試以下操作。 struct student*用於迭代10個學生,其中students指向10個連續存儲的學生中的第一個。需要注意的是s++struct student尺寸增加指針:

void generate(struct student* students){ 
    /* 
    *Generate random ID and scores for 10 students, ID being between 0 and 
    * scores equal to (id* 10 % 50) 
    */ 
    struct student* s = &students[0]; 
    for (int i=0; i<10; i++) { 
     s->id = i; 
     s->score = (i*10)%50; 
     s++; 
    } 
} 

注意 - 由DYZ指出的 - 你也可以通過直接使用可變students遍歷;這是一個喜歡的問題,是否想保留原來傳遞的值:

void generate(struct student* students){ 
    for (int i=0; i<10; i++) { 
     students->id = i; 
     students->score = (i*10)%50; 
     students++; 
    } 
} 
+1

爲什麼你需要'struct student * s =&students [0];',又一次?只要刪除這條線,一切都會起作用。 – DyZ

+0

@DYZ:你說得對;只是我不喜歡直接操作參數; –

+0

它不是你改變的參數,而是它的一個副本,無論如何。 – DyZ