简体   繁体   English

rand() / srand() 一直给我零

[英]rand() / srand() keeps giving me zero

I have 2 functions that generate random numbers (first function generates 5 random sets, second function only one. I called srand(time(NULL)) in the first one, and by doing so I didn't have to call it again in the second function.我有 2 个生成随机数的函数(第一个函数生成 5 个随机集,第二个函数只生成一个。我在第一个函数中调用了 srand(time(NULL)),这样我就不必在第二个功能。

Problem is, for the second function I keep getting zero (first function is fine).问题是,对于第二个函数,我一直得到零(第一个函数很好)。 Here are the two functions (these are snippets of the entire code, too long to post it all, unless you guys would need it let me know).这是两个函数(这些是整个代码的片段,太长了无法全部发布,除非你们需要它让我知道)。

Edit: I #included < ctime > if you're curious, so that's not the issue.编辑:我 #included < ctime > 如果你很好奇,所以这不是问题。

 int Winning_Numbers(int generated[])
 {
     int amount = 5;
     int winning_ticket = generated[amount];

     srand(time(NULL));

     for(int x = 0; x < amount; x++)
     {
         generated[x] = (rand() % 69) + 1;

         while (generated[x] < 1 || generated[x] > 69)
         {
             generated[x] = (rand() % 10) + 1;
         }

         if (x > 0)
         {
             for(int check_number = 0; check_number < x; check_number++)
             {
                 while (generated[x] == generated[check_number])
                 {
                     generated[x] = (rand() % 10) + 1;
                 }
             }
         }
     }

     return winning_ticket;
 }

 int Powerball(int powerball_generated)
 {
     powerball_generated = (rand() % 26) + 1;

     if (powerball_generated < 1 || powerball_generated > 26)
     {
         powerball_generated = (rand() % 10) + 1;
     }

     return powerball_generated;
 }

Your code has lots of little problems, but the one you're asking about is that in your main function you have您的代码有很多小问题,但您要问的是在您的main功能中

int powerball_number;
Powerball(powerball_number);

Here you are passing the value of powerball_number to the Powerball() function as an argument.在这里,您将powerball_number的值作为参数传递给Powerball()函数。 But what you want to do is have Powerball() return a value and assign that to the powerball_number variable.但是您想要做的是让Powerball()返回一个值并将其分配给powerball_number变量。 So you should write所以你应该写

powerball_number = Powerball();

instead.反而。 Also change the Powerball() function to just还将 Powerball() 函数更改为

int Powerball()

since it doesn't need to take an argument at all.因为它根本不需要争论。

As a side note, it's much easier for answerers if you can show a small but complete piece of code, that shows your problem, right in your question.作为旁注,如果您可以显示一小段但完整的代码,就可以在您的问题中显示您的问题,那么回答者会容易得多。 Here, the key to your problem showed only in the pastebin fragment, the link to which was hiding in one of the comments, and which it took me a while to find..在这里,您的问题的关键仅显示在 pastebin 片段中,链接隐藏在其中一条评论中,我花了一段时间才找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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