Trying to take 1 random digit at a time

独自空忆成欢 提交于 2020-01-06 19:45:32

问题


I am new to cpp programing, and new to stackoverflow.

I have a simple situation and a problem that is taking more time than reasonable to solve, so I thought I'd ask it here.

I want to take one digit from a rand() at a time. I have managed to strip of the digit, but I can't convert it to an int which I need because it's used as an array index.

Can anyone help? I'd be appreciative.

Also if anyone has a good solution to get evenly-distributed-in-base-10 random numbers, I'd like that too... of course with a rand max that isn't all 9s we don't have that.

KTM


回答1:


Well you can use the modulus operator to get the digit of what number rand returns.

int digit = rand()%10;

As for your first question, if you have a character digit you can subtract the value of '0' to get the digit.

int digit = char_digit - '0';



回答2:


If one wants a pedantic even distribution of 0 to 9 one could

  1. Assume rand() itself is evenly distributed. (Not always a good assumption.)

  2. Call rand() again as needed.

    int ran10(void) {
      const static int r10max = RAND_MAX - (RAND_MAX % 10);
      int r;
      while ((r = rand()) >= r10max);
      return r%10;
    }
    

Example:
If RAMD_MAX was 32767, r10max would have the value of 32760. Any rand value in the range 32760 to 32767 would get tossed and a new random value would be fetched.




回答3:


While not as fast as modulo-arithmetic implementations like rand() % 10, this will return evenly distributed integers and avoid perodicity in the least significant bits that occur in some pseudo-random number generators (see http://www.gnu.org/software/gsl/manual/html_node/Other-random-number-generators.html).

int rand_integer(int exclusive_upperbound)
{
        return int((double)exclusive_upperbound*rand()/RAND_MAX);
}


来源:https://stackoverflow.com/questions/21210682/trying-to-take-1-random-digit-at-a-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!