【问题标题】:How to generate random ID and test scores for a a struct of 10 students如何为 10 名学生的结构生成随机 ID 和考试成绩
【发布时间】:2017-06-08 14:31:21
【问题描述】:

这是我的第一个 C 编程作业,我很困惑如何实现随机数。在我的程序中,我已经创建了一个 struct student,并创建了一个包含 10 个学生的数组。现在我必须为这 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),填充作为参数传递的 10 个学生的数组的 id 和 score 字段。每个学生都应该有一个对应于他们在数组中的索引的 id(即数组中的第一个学生应该有 id 0). 如果每个学生的id都是x,那么学生的分数应该是(10 * x) % 50。"

【问题讨论】:

  • 指令在哪里说“随机”? “与它们在数组中的索引相对应的 id”不是随机的,“分数应该是 (10 * x) % 50”也不是随机的。
  • 指令没有说“随机数”。它特别说明数字将基于数组中的索引。
  • 看到这也是我感到困惑的地方,因为他给学生的骨骼的 cmets 说是随机的,但实际的说明不是
  • @McGradyMan 所以这是要求的问题。 Stackoverflow 无法帮助您解决这个问题。只有您的教学人员才能做到这一点。去问问他们。

标签: c arrays memory-management random struct


【解决方案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++;
    }
}

【讨论】:

  • 为什么还需要struct student* s = &amp;students[0];?只需删除此行,一切都会正常。
  • @DYZ:你是对的;不直接对参数进行操作只是我的喜好;
  • 它不是您更改的参数,而是它的副本。
  • 但是,如果您删除该行,它不会初始化 s 变量。我应该如何初始化它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多