c++代码结果输出不同,具体取决于执行方法调试与运行

标签 c++ random srand

这个程序生成随机字符串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/

相关文章:

c++ - 访问Qt3DRender::QBuffer的数据时数据指针为<QArrayData::shared_null+24>

c++ - 以下3个opencv Mat实例有什么区别?

java - 创建一组均匀分布的随机数

c++ - 不涉及时间的 rand() 种子?

c++ - 在 C++ 中欺骗 std::cin

c++ - 无法在 RichEdit 中保留换行符

C++ 在 if 语句中使用 rand

c# - 将字节数组写入 C#.NET 中现有文件的中间

c++ - rand () for c++ with variables

c - 查看随机序列中的下四个数字(使用 srand 和 rand)