简体   繁体   English

rand()在我的自定义函数中不返回任何值

[英]rand() returns no value in my custom function

Despite having set srand() only once as pointed by similar Q/A about rand() 尽管针对类似rand()的Q / A指出设置srand() 一次
I think the following rand does not return a value for my customized random function. 我认为以下rand不会为我的自定义随机函数返回值。

Anyway my purpose was to generate a few random numbers 无论如何,我的目的是生成一些随机数
and right after their appearance to count +1 at an array (to calculate their frequency later on) 并且在它们出现之后立即在数组中计数+1(以便稍后计算它们的频率)

One represents (5x)+1 at freq[] array 一个代表在freq []数组上的(5x)+1

I have read documentation about rand()/srand but I cant figure out the error. 我已阅读有关rand()/ srand的文档,但无法弄清错误。

Thanks for your patience! 谢谢你的耐心!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000



int RandomInteger(int low , int high);
main()
{
    int freq[9]={0},i,j,number,div;

    srand((int)time(NULL));
    for(i=0;i<N;i++)
        number=RandomInteger(1,9);
    switch(number){ 
    case 1:
        freq[0]+=1;
        break;
   case 2:
        freq[1]+=1;
        break;
   case 3:
        freq[2]+=1;
        break;
   case 4:
        freq[3]+=1;
        break;
   case 5:
        freq[4]+=1;
        break;
   case 6:
       freq[5]+=1;
       break;
   case 7:
       freq[6]+=1;
       break;
   case 8:
      freq[7]+=1;
      break;
   case 9:
      freq[8]+=1;
      break;
   default:
    ; 
   }
for(i=0;i<9;i++){
   div=freq[i]/5;
   printf("%d|",div);
   for(j=0;j<div;j++) 
       printf("*"); 
   printf("\n"); 
   }

}

int RandomInteger(int low , int high)
{
    int k;
    double d;
    d=(double)rand()/((double)RAND_MAX+1);
    k=(int)(d*(high-low+1));

    return low+k;
}

You problem is this: 您的问题是这样的:

for(i=0;i<N;i++)
 number=RandomInteger(1,9);

It should have 应该有

for(i=0;i<N;i++) {
 number=RandomInteger(1,9);
..
..
}

Otherwise it runs it N times (same line), but never goes to the switch until it finishes the loop 否则,它将运行N次(同一行),但直到完成循环后才进行switch

In your code high is set to 1 and low is set to 9 this will result in a negative k. 在您的代码中,high设置为1,low设置为9,这将导致负数k。 The return will be outside of the range of your cases and will fall to default. 退货将不在您的情况范围之内,并且将默认为退货。

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

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