Home > Backend Development > C++ > body text

How to Generate Random Double Numbers with Decimals in C ?

Mary-Kate Olsen
Release: 2024-11-03 11:33:03
Original
862 people have browsed it

How to Generate Random Double Numbers with Decimals in C  ?

Generating Random Double Numbers with Decimals in C

In C , generating random numbers between two doubles in the format "xxxxx,yyyyy" involves utilizing the library features introduced with C 11 and the TR1 extensions.

Solution Outline

To generate random numbers in the specified format, follow the steps below:

  1. Initialize the lower bound and upper bound of the desired range.
  2. Create an instance of std::uniform_real_distribution with the specified bounds.
  3. Instantiate a random number generator engine using std::default_random_engine.
  4. Generate a random double number within the specified range using the distribution and random engine.

Code Example

<code class="cpp">#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound, upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}</code>
Copy after login

Additional Information

For further insights into random number generation in C , refer to the following resources:

  • [John D. Cook's "Random number generation using C TR1":](https://www.johndcook.com/blog/2011/08/19/random-number-generation-using-cpp-tr1/)
  • [Stroustrup's "Random number generation":](https://www.stroustrup.com/4282.html)

The above is the detailed content of How to Generate Random Double Numbers with Decimals in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template