1

I want a table of four values between 1 to 6.

I'm using: rand() % 6 + 1;

This should give values between 1 and 6.

Except if rand() generates the value 0.

  1. I keep getting 7's. I don't want any 7's

  2. What is the range of rand? How I prevent it from generation any 0 values?

  3. Alternative solutions are quite welcome.

  4. My teacher gave us the clue of using "random".
    We use Borland C++ Builder 5 at school.
    I am using Dev-C++ 5.3.0.3 at home.
    I find there are a few differences to how they work, which I find strange..
    I can't use random(), it gives me not declared in scope...

    int main (){
    
        int I;
        int Fasit[3];
    
        srand (time(NULL) );
    
        for(I=0; I<4; I++) {
            Fasit[I]=rand() % 6 + 1;
        }
    
        std::cout << Fasit[0] << " " << Fasit[1] << " " << Fasit[2] << " " << Fasit[3] << " ";
    
        return 0;
    }
    

Some values I get:

2 6 1 7  
5 2 1 4  
5 2 1 4  
5 2 1 4  
1 3 1 6  
5 3 3 7  
5 3 3 7  
5 3 3 7

7 shouldn't be possible, should it?

PS: I know my print is ham fisted, I will make it a bit more elegant once the number generation works.

lmcanavals
  • 2,339
  • 1
  • 24
  • 35
DrOnline
  • 741
  • 1
  • 7
  • 9

4 Answers4

9

Consdier these lines:

int Fasit[3];
for(I=0; I<4; I++) {
  Fasit[I]

You declare an array of three entries, which you write to four times.

Try your program again, but with:

int Fasit[4];
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
2

You only have 3 elements in Fasit[3]; When you write to Fasit[3], you are in the realm of undefined behavior, which in this case manifests it self with apparent contradiction.

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
  • Thanks! I had misunderstood the relationship between index and table size, I thought 3 means size 4 with, 0, 1, 2, 3... – DrOnline Jan 30 '13 at 20:42
2
int Fasit[3];

You are creating an array of size 3, which can be accessed with indexes 0, 1 or 2 only.

You are writing and reading Fasit[3], which has an undefined behaviour. When a behaviour is undefined, you are bound to obtain weird results. This is it.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
2

Fasit[3] allows you to access only Fasit[0], Fasit[1], and Fasit[2].

Accessing Fasit[3], either for reading and writing, is undefined behavior. Your code is both writing and reading to Fasit[3] :-). The program is accessing the array out-of-bound. Fix it!

As to why 7 is printed, that is just coincidence. Note that Fasit[0-3] is always printed in the range 1-6 as you expected.

See also:

Community
  • 1
  • 1
Arun
  • 19,750
  • 10
  • 51
  • 60
  • Good point about the 0 to 3 indexes being within the range. I did notice that but thought it was coincidental. Program works now! – DrOnline Jan 30 '13 at 20:45