【问题标题】:How to create a linked list that generates random numbers until it generates a specific number如何创建一个生成随机数的链表,直到它生成一个特定的数字
【发布时间】:2021-12-02 08:22:27
【问题描述】:

系统提示我创建一个生成数字 0-50 的链表。当列表生成 49 时,它应该打印出列表而不是打印 49。我的问题是试图弄清楚如何制作循环,以便它可以实际执行此任务。

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

void printList();
struct Node {
    int data;
    struct Node* next;
};

int main() {
    srand(time(0)); //srand sets starting value for series of random ints
    
    int x = rand()%50 + 1; //gets random number in range 1-50, including 50
    
    struct Node* head = (struct Node*)malloc(sizeof(struct Node));
   
    head->data = x; //assigns head to the random value between 0 and 50
    head->next = NULL;
    
    printList(head); //calls funtion to print list
    
    return 0;
}

void printList (struct Node* n){
    while (n != NULL){
        printf(" %d ", n->data);
        n = n->next;
    }
}

【问题讨论】:

  • “如何制作循环for (i=0; i &lt; 50; i++)?请澄清您对“制作循环”的哪个特定部分有困难?
  • @kaylum 我不确定循环的条件是什么,因为我假设列表会一直持续下去,直到生成数字 49 为止。跨度>
  • 我明白了。抱歉,我将您的问题误解为“直到生成 49 个数字”。我看到一个答案已经发布,看起来不错。

标签: c loops linked-list iteration random-seed


【解决方案1】:
int rnd;
while((rnd = rand() % 50) != 49)
{ 
    add_tolist(rnd);
}

printlist();

【讨论】:

  • 在我的代码中我有 x=rand() % 50,所以我会用 x 替换 rnd 并且仍然可以吗?
  • 另外,这只需要我在 main 之外创建一个 add_tolist 函数吗?抱歉,如果我的问题看起来很愚蠢,我真的想澄清一下
猜你喜欢
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2023-01-03
  • 2013-01-03
  • 2018-04-21
  • 1970-01-01
  • 2013-05-20
  • 2021-05-31
相关资源
最近更新 更多