How to Generate the random numb开发者_StackOverflow社区er from 0.5 to 1.0 .
You can try:
float RandomBetween(float smallNumber, float bigNumber)
{
float diff = bigNumber - smallNumber;
return (((float) rand() / RAND_MAX) * diff) + smallNumber;
}
You should be able to use something like:
double x = ((double)rand()) / ((double)RAND_MAX) / 2.0 + 0.5;
The division by RAND_MAX
gives you a value from 0 to 1, dividing that by two drops the range to 0 to 0.5, then adding 0.5 gives you 0.5 to 1. (inclusive at the low end and exclusive at the top end).
Some thing like bellow will help you.
double random(double start, double end)
{
double moduleValue = ((end - start) *10); //1.0 - .5 --> .5 -->> 5
double randum = rand() % moduleValue; // restrict the random to your range
//if rendum == 2 --> .2 + .5 --> .7 in the range .5 -- 1.0
return (randum / 10) + start; // make your number to be in your range
}
Test code for clarification
#include <stdio.h>
#define RAND_NUMBER 14
#define INT_FLAG 10
int main (int argc, const char * argv[]) {
// insert code here...
double start = .5;
double end = 1.0;
double moduleValue = ((end - start) * INT_FLAG);
int randum = (RAND_NUMBER / moduleValue);
double result = ((double)randum/INT_FLAG) + start;
printf("%f",result);
printf("Hello, World!\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
main()
{
int i;
double b,n;
srand(getpid());
n=rand()%51+50;
b=n/100;
printf("%f\n",b);
}
精彩评论