Gary Wessle <(E-Mail Removed)> wrote:

> I am not sure what wrong I am doing, followed the link provided by

> Marco, which was

> http://cplus.about.com/od/advancedtu.../aa041303c.htm

>

> the following puts out zeros on my screen. only zeros no mater how

> many times I run it.
#include <iostream>

> #include <ctime>

> using std::time;
using std::cout;

> int main() {

>

> int x;

> const int N = 100;

> srand( static_cast<unsigned> (time( NULL )) );

> for (int i = 0; i < 4; i++) {

> x = static_cast<int> ( N*rand())/(RAND_MAX+1) ;
Let's rearrange your spacing:

x = static_cast<int>(N*rand()) / (RAND_MAX+1);

So, you are taking the value of N*rand(), and then casting it to an int.

Then you are dividing it by (RAND_MAX+1), which is also an int.

Therefore you have an int/int, so the division truncates, resulting in a

zero.

I would try casting the result of N*rand() to a double, then performing

the (floating-point) division, then casting THAT result to an int:

x = static_cast<int>(static_cast<double>(N*rand()) / (RAND_MAX+1));

Of course, you could break this up into smaller steps.

> cout << x << endl;

> }

> }
--

Marcus Kwok

Replace 'invalid' with 'net' to reply