以下是我所指的代码:
int main ()
{
// Random training sets for XOR -- two inputs and one output
cout << "topology: 2 4 1" << endl;
for (int i = 2000; i >= 0; --i) {
int n1 = (int) (2.0 * rand() / double(RAND_MAX));
int n2 = (int) (2.0 * rand() / double(RAND_MAX));
{
int t = n1 ^ n2; // should be 0 or 1
cout << "in: " << n1 << ".0 " << n2 << ".0 " << endl;
cout << "out: " << t << ".0" << endl;
}
}
}
对于n1
和n2
来说,这两行似乎相同:
int n1 = (int) (2.0 * rand() / double(RAND_MAX));
int n2 = (int) (2.0 * rand() / double(RAND_MAX));
但是,当我在(int) (2.0 * rand() / double(RAND_MAX))
时,答案似乎总是显示为1。
那么这条线怎么可能是真的:
int t = n1 ^ n2; // should be 0 or 1
代码的输出显示为i / e:
in: 1.0 0.0
out: 1.0
in: 0.0 1.0
out: 1.0
in: 1.0 0.0
out: 1.0
in: 0.0 1.0
out: 1.0
in: 0.0 0.0
但(1 ^ 1)
与t = n1 ^ n2
一样,总是将其作为0.那么上述输出如何可能?或者我只是没有足够地管理这些线条(我每次都做了很多次,每次10次)。
修改
我不明白的是,每次我编译并运行第cout << (int) (2.0 * rand() / double(RAND_MAX));
行时,它都输出1而n1
和n2
都等于(int) (2.0 * rand() / double(RAND_MAX));
所以怎么可能{{1}曾经出现过1?然而就是。
答案 0 :(得分:1)
随机数生成器rand()
将始终为您提供1次运行程序..如果您不想让它第一次给1,那么将randon数生成器种子设置为不同的值因为现在它总是使用相同的默认种子。调用命令srand()
来改变种子值,你可以通过将随机数生成器种子设置为你的计算机时钟来使它更随机
使用此代码
#include <ctime>
srand((unsigned)time(0));
我认为它没有任何问题,我在一行上做了也许你的眼睛只是在欺骗你,http://ideone.com/WaMihm
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
// Random training sets for XOR -- two inputs and one output
cout << "topology: 2 4 1" << endl;
for (int i = 2000; i >= 0; --i) {
int n1 = (int) (2.0 * rand() / double(RAND_MAX));
int n2 = (int) (2.0 * rand() / double(RAND_MAX));
int t = n1 ^ n2; // should be 0 or 1
cout << "[A]in: " << n1 << " [B]in: " << n2 << " out: " << t << endl;
}
}
Output:
topology: 2 4 1
[A]in: 1 [B]in: 0 out: 1
[A]in: 1 [B]in: 1 out: 0
[A]in: 1 [B]in: 0 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 1 [B]in: 1 out: 0
[A]in: 1 [B]in: 1 out: 0
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 0 out: 0
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 0 out: 0
[A]in: 0 [B]in: 0 out: 0
[A]in: 1 [B]in: 0 out: 1
[A]in: 1 [B]in: 1 out: 0
[A]in: 1 [B]in: 0 out: 1
[A]in: 1 [B]in: 1 out: 0
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 1 [B]in: 1 out: 0
[A]in: 0 [B]in: 1 out: 1
[A]in: 0 [B]in: 0 out: 0
[A]in: 1 [B]in: 1 out: 0
[A]in: 0 [B]in: 1 out: 1
[A]in: 1 [B]in: 0 out: 1
[A]in: 0 [B]in: 1 out: 1
[A]in: 1 [B]in: 0 out: 1
[A]in: 0 [B]in: 0 out: 0
[A]in: 0 [B]in: 0 out: 0
[A]in: 0 [B]in: 1 out: 1
答案 1 :(得分:0)
编辑我不理解的是每次我编译并运行行cout&lt;&lt; (int)(2.0 * rand()/ double(RAND_MAX));它输出1和n1和n2都等于(int)(2.0 * rand()/ double(RAND_MAX));所以t = n1 ^ n2怎么可能会出现1而它还有
第一次时间调用它,输出1。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
for (int i = 0 ; i < 10; ++i)
{
int j = (2.0 * rand () / double (RAND_MAX));
printf ("%d\n", j);
}
}
给出:
1
0
1
1
1
0
...
由于rand
的实施可能会有所不同,您的输出也可能不同。
因为每次运行程序时随机数生成器都以相同的状态启动,所以每次都会生成相同的第一个结果。但是调用rand
会改变状态,因此从同一个实例调用rand
会产生不同的输出。