-1
int Width()
{
    int r = 0;
     r = rand();
     if (r <= 3640)
     {
         r = (r % (10 - 1 + 1)) + 1;
         printf("%d", r);
     }
   return number;
}

So I have this C code here to practice using the rand() function. As I understand it the 10-1 should be the "high"-"low" for my range and then the +1 at the end should shift it into the range that I would like. The program does throw any errors though. It just crashes.

JMBTaylor
  • 33
  • 1
  • 7
  • 1
    man printf..................... – Martin James Apr 23 '16 at 21:55
  • I'm voting to close this as too broad, because you're misusing `printf`, which is definitely one of the first (if not the first) library function C programmers learn. Hence, I don't really think we can point you to a simple answer other than: read your code carefully, and understand what all the two functions you use do. – Marcus Müller Apr 23 '16 at 21:57
  • Sorry. That was a typo. I fixed it in the code block now though. – JMBTaylor Apr 23 '16 at 22:04
  • 1
    What does the code do now after that fix? – dbush Apr 23 '16 at 22:06
  • Crashes, the code here was off only because of the way I copied it over. – JMBTaylor Apr 23 '16 at 22:09
  • 1
    `(10 - 1 + 1)` is the same as just `10`. And what do you mean by "it just crashes"? Since this is just a function in a bigger program, from what you show, it's likely the problem is now elsewhere in your code. I suspect one problem is going to be that you declared this function to return a value (`int Width()`) but never return anything. It's not clear what the caller expects, but it will, indeed, get something rather random. – lurker Apr 23 '16 at 22:16
  • I'm not sure how this particular block was causing a crash since I changed it to the code I have pasted in the bottom. I also forgot to include the return function. all add it. – JMBTaylor Apr 23 '16 at 23:03

1 Answers1

0

Poking around on another site and I think I may have figured it out.

int number;
/* initialize random seed: */
srand ( time(NULL) );
/* Generate a random number: */
number = rand() % 10 + 1;
printf("%d", number);

This is the block of code that I modified slightly and will work for what I need. I didn't realize that I had to initialize rand() with srand(time(NULL)) before using it. Then I found out that I was over thinking the range portion and fixed that with number = rand() % 10 + 1; With 10 being the max and 1 being the minimum.

JMBTaylor
  • 33
  • 1
  • 7
  • 1
    No, you have not figured it out. If the code you posted in this answer is the function code, you should not call `srand()` in the function, but once only, at the start of `main`. – Weather Vane Apr 23 '16 at 23:47
  • it worked the way it was but I'll change it just to be sure – JMBTaylor Apr 24 '16 at 01:31