简体   繁体   中英

Modulo gives impossible value

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.

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];

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.

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM