... and I don't know why.
I'm just getting back into C++ programming after years of not using it at all. I tried to make a simple program that
- Creates 10 random numbers between 0-99 and prints them
- Categorizes each number by range
- prints the sum of all numbers.

The problem is that every time I run the program, it consistently gives the exact same output and I don't know why!

I uploaded it so you can see what I mean: http://jerail.ca/cgi-bin/random.cpp.cgi

And here's the source code:

/*
	Some random numbers
*/
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
  int i; // for use in loop
  int numbers[10]; // to store our random numbers
  int cat[3] = { 0, 0, 0 }; // category of size
  int sum = 0; // sum of all numbers
  for(i=0;i<10;i++) // loop thru 10 times...
  {
    numbers[i] = (rand()%100); // get a rand num
    cout << numbers[i] << endl; // print rand num to screen (+ linebreak)
    sum = sum + numbers[i]; // add rand num to total sum
    if(numbers[i]>=0 && numbers[i]<=33)
      cat[0] = cat[0] + 1; // if 0<x<33 increment counter
    else if(numbers[i]>=34 && numbers[i]<=70)
      cat[1] = cat[1] + 1; // if 34<x<70 increment counter
    else if(numbers[i]>=71 && numbers[i]<=99)
      cat[2] = cat[2] + 1; // if 71<x<99 increment counter
    else
    {
      cerr << "ERROR" << endl; // otherwise print error
      return -1; // and kill program
    }
  }
  cout << "A (0-33):  " << cat[0] << endl 
       << "B (34-70): " << cat[1] << endl 
       << "C (71-99): " << cat[2] << endl // output totals of each category...
       << "Sum: " << sum << endl; // ... and total sum of all numbers

  return 0; // return success
}

#include <ctime> and call srand((unsigned)time(0)); (once) before you call rand().

Its because random numbers are not randomly generated...

Ok, thanks guys. Didn't realize srand() was a requirement. I've gotten used to programming in more loosely-typed languages :[

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.