这个程序生成随机字符串3次
在 eclipse 中使用“step into”进行调试时,结果是唯一且不同的
刚执行3次结果都是同一个字符串
为什么结果会因执行方式、调试与编译运行而不同?
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <ctime>
#include <cstdlib>
string generaterandomstring(int length){
int i, x, alphabetsize, asciioffset;
string s1;
alphabetsize = 26; // size of all lower case letters
asciioffset = 97; // lower case letters start at 97
srand ( time(NULL) );
for ( i = 0; i < length; i++ )
{
//generate random number
x = rand() % alphabetsize + asciioffset;
cout << "x: " << x;
//get a letter
cout << " char: " << char(x);
//append it to string
s1 = s1 + char(x);
cout << " s1: " << s1 << endl;
}
return s1;
}
int main() {
int i;
string s1;
int length = 3;
srand ( time(NULL) );
for ( i = 0; i < length; i++ )
{
s1 = generaterandomstring(length);
cout << "i is: " << i << " from main s1: " << s1 << endl;
cout << rand() % 10 << endl;
}
cout << "!The End!" << endl; // prints !!!Hello World!!!
return 0;
}
最佳答案
http://cplusplus.com/reference/clibrary/cstdlib/srand/
The pseudo-random number generator is initialized using the argument passed as seed.
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand. Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.
http://cplusplus.com/reference/clibrary/ctime/time/
Get the current calendar time as a time_t object.
关于c++代码结果输出不同,具体取决于执行方法调试与运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12303224/