コードを実行すると、rand()
関数は同じ非乱数を生成するようです(私の意図はvalue
に乱数を生成することです)。 rand()
の代わりに仮パラメータlength
を使用すると、コードが機能しているように見えます(数値が小さくなっているようです)。どこが間違っていますか?リンクリスト付きの再帰関数でrand()を使用する
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node{
int value;
struct node *next;
};
struct node *construct(int);
int main(){
struct node *list = construct(5);
while(list){
printf(" %i\n", list->value);
list = list->next;
}
return 0;
}
//It builds a list of "length" items recursively
struct node *construct(int length){
struct node *node = (struct node *) malloc(sizeof(struct node));
srand(time(NULL));
node->value = rand(); /* unclear part of code */
if(length - 1){
node->next = construct(length - 1);
}
return node;
}
/* missing the code to free memory */
/* example of output */
837240329
837240329
837240329
837240329
837240329
'rand'のドキュメントを読むのはどうですか? – Olaf
「*同じ*」と同じ乱数?あなたは各ノードに同じ番号を持っていますか?各実行で同じ番号のシーケンス?あなたが投稿しているのは、要求された出力がありません。 – Prune
'main'の先頭で' srand(time(NULL)); '* once *を呼び出します。 –