Hi all,

I have tried to make a little example of a random number generator for c++. However, as I am quite new in this language I do not know its peculiarities.

Here is the code

//g++ -o ran ran.cpp

#include <iostream>

using namespace std;

int main () {
int num;
  for (int i = 0; i < 10; i++) {
    num = rand() % i;
    cout << num << endl;
  }
}

This little code gives the above error. I have tried replacing the "i" variale with an specific number and it works.

Can anybody tell me why this happens?

I am using the following g++
gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-54)

Thank you!

Recommended Answers

All 4 Replies

Your code executes the line 'rand() % 0', which is a divide-by-0 error. Start your for loop at i=1 or something of that nature.

commented: Nice catch +19

OMG

It was a stupide question

Thank you for answering! ;)

Random numbers need to use srand( ) otherwise you get the same
number each time

there are a few posts on this and a quick search will show you
some demo code
you should get the system time
and call
srand(time);

OMG

It was a stupide question

Thank you for answering! ;)

i recall some recent snafu at NASA causing a significant failure, and being traced to a divide-by-zero error. (or, maybe i dreamed it. i'm not sure now...) but anyhow it's not a stupid question. it's a good lesson.

For instance, I just had to come into work all day sunday to revalidate a production system revision that failed because I had accidentally inserted a single "stupid semicolon" immediately after a FOR conditional statement.

point is, everyone needs to check their work, because these "stupid errors" can get by any of us. your learning now, will save you time and money in the future.

.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.