[英]Random-filled vector always returns the same numbers
我是C語言的新手,嘗試用隨機整數填充向量,然后輸出。 但是,向量似乎總是用相同的數字填充。 要真正獲得隨機付款,我需要更改什么? 沒有限制,數量只能在long的值范圍內。 這是我的代碼:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <time.h>
int main()
{
long x = 20;
long y = 12;
std::vector<long> entries;
//initialize simple random number generator using current time
srand(time(NULL));
for (int step = 0; step < x; step++) {
entries.push_back(rand());
++entries[step];
}
for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
printf("%ld\n", i);
}
return 0;
}
編輯: 我想解決使用普通C不是c ++的問題!
代碼中的主要問題是在上一個循環中
for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
printf("%ld\n", i);
}
您不是從向量打印值,而是指向它的迭代器
將循環內的行更改為printf("%ld\\n", *i);
要解決這個問題。
更好的是,您可以使用范圍循環使其更簡單
for(auto& number : entries){
std::cout<<number<<'\n'; //or printf("%ld\n",number), like in your code
}
如果您希望解決方案是純C語言,則需要使用數組而不是向量。
我在這里缺少一些信息,但是使用srand()和rand()的基本C程序看起來像這樣:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#define NB_ENTRIES (20)
#define RANDOM_MAX_RANGE (50) // you should update that
// Don't use srand(time(NULL)) because if you start many time this
// program too quickly, you'll have the same values in all instances.
void Randomize(void)
{
struct timeval time;
gettimeofday(&time,NULL);
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
}
// Returns a value between 0 and toNumber-1
// Thanks to Bathsheba for pointing out an error with my first version.
int RandomInt(int toNumber)
{
return (int)(rand()/(RAND_MAX + 1.0) * toNumber);
}
// This better but slower version of RandomInt() will ensure
// an even distribution of random values if toNumber is
// greater than around three quarter of RAND_MAX
// NOTE : toNumber must be between 0 and RAND_MAX.
int BetterRandomInt(int toNumber)
{
const int randomSize = RAND_MAX / toNumber;
int returnValue;
do
{
returnValue = rand() / randomSize;
}
while (returnValue >= toNumber);
return returnValue;
}
int main(void)
{
int entries[NB_ENTRIES];
int step;
Randomize();
for (step = 0; step < NB_ENTRIES; step++)
{
entries[step] = RandomInt(RANDOM_MAX_RANGE);
// entries[step] = BetterRandomInt(RANDOM_MAX_RANGE);
}
for (step = 0; step < NB_ENTRIES; step++)
{
printf("%d\n", entries[step]);
}
return 0;
}
請注意,我使用的是固定數量的條目。 您可以使用指針和malloc()使數組動態化。 僅在需要時發表評論,但我認為這超出了問題的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.