0到100的随机数如何取?
要求一般的随机“且不允许重复”数的取法,想了没啥思路,有没有不用库函数就可以实现的简单算法?
这个很简单嘛,就是有一个专门的函数。是管这个的,
#include <iostream> #include <vector> #include <windows.h> using namespace std; int main(int argc, char* argv[]) { vector<int> vec; for(int i = 0; i <= 100; ++i) vec.push_back(i); srand(GetTickCount()); for(int j = 0; j <= 100; ++j) { int index = rand() % vec.size(); vector<int>::iterator iter = vec.begin() + index; cout << *iter << " "; vec.erase(iter); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand((unsigned)time(NULL)); const int MAX_SIZE = 101; const int VALUE_SIZE = 101; const int HIT_COUNT = 1000; int array[MAX_SIZE] = {0}; int i=0; //init for(i=0;i<MAX_SIZE;i++) { array[i]=i; } int nHit_Count = 0; int index = 0; int *pItem = array; //hit while(nHit_Count<HIT_COUNT) { index = rand()%MAX_SIZE; *pItem = *pItem^array[index]; array[index] = *pItem^array[index]; *pItem = *pItem^array[index]; pItem = array+index; nHit_Count++; } //output for(i=0;i<VALUE_SIZE;i++) { printf("%d ",array[i]); } return 0; }