Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,878 questions

51,803 answers

573 users

How to generate random float in specific range with C

3 Answers

0 votes
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
  
float getRandomFloat(float min, float max) {
    float f0to1 = (float)rand() / (float)(RAND_MAX); // 0 - 1.0
     
    return min + f0to1 * (max - min);      
}
 
int main()
{
    srand((unsigned int)time(NULL));
  
    for (int i = 0; i < 20; i++) {
        float f = getRandomFloat(2.0f, 5.0f);
        printf("%f\n", f);
    }
  
    return 0;
}

   
/*
run:
   
2.680616
3.275257
4.114973
2.575413
4.145402
3.948520
3.409535
2.458676
2.829132
2.349118
4.605762
4.947170
4.409251
2.788041
4.350597
3.487345
3.458914
3.048046
2.423299
4.606344
   
*/

 



answered Jun 1, 2022 by avibootz
edited Apr 19, 2025 by avibootz
0 votes
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
  
float getRandomFloat(float min, float max) {
    return min + ((float)rand() / RAND_MAX) * (max - min);
}
 
int main()
{
    srand((unsigned int)time(NULL)); // Seed the random number generator
  
    for (int i = 0; i < 20; i++) {
        float f = getRandomFloat(2.0f, 5.0f);
        printf("%f\n", f);
    }
  
    return 0;
}

   
   
/*
run:
   
2.097344
4.005432
4.993202
4.226770
3.402695
3.654019
4.899565
3.192528
4.325018
2.650082
2.161607
3.929626
4.107109
4.985487
2.553310
3.787764
2.205874
4.649768
3.691223
3.591495
   
*/

 



answered Apr 19, 2025 by avibootz
0 votes
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
  
float getRandomFloat(float min, float max) {
    int scale = 1000000; // Scale factor for precision
    
    return min + ((float)(rand() % scale) / scale) * (max - min);
}
 
int main()
{
    srand((unsigned int)time(NULL)); // Seed the random number generator
  
    for (int i = 0; i < 20; i++) {
        float f = getRandomFloat(2.0f, 5.0f);
        printf("%f\n", f);
    }
  
    return 0;
}

   
   
/*
run:
   
2.150996
4.891793
2.262305
4.750775
4.300043
3.892673
3.634532
4.773443
4.167854
4.800653
4.420640
3.934223
4.394399
4.500620
4.193135
4.468163
2.924231
4.097465
2.994896
3.588470
   
*/

 



answered Apr 19, 2025 by avibootz

Related questions

...