Mitko
Mitko

Reputation: 11

How to use random precision numbers

Hello I need help writing my program. I am trying to figure out how I should make it so when I type two range numbers (one is a maximum and one is a minimum) which the program will recognize and output a random number in between one of them. So far I have figured it out but it works only for whole numbers, I cant seem to find a way for those numbers to be with precision of 2 lets say.

#include "pch.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int  a, b, c, d;
srand(time(0));
cout << "Welcome to the game." << endl;
cout << "Please enter number range" << endl;
cout << "Highest number:";
cin >> c;
cout << "Lowest number:";
cin >> d;
b = d + (rand() % (c - d + 1));
cout << "Enter your guess:";
cin >> a;
unsigned int count = 0;
while (a < b) {
    cout << "Your number is lower than the correct one." << endl;
    cout << "Please try again:";
    cin >> a;
    count++;
}
while (a > b) {
    cout << "Your number is higher than the correcnt one." << endl;
    cout << "Please try again:";
    cin >> a;
    count++;
}

cout << "Your number is the correct one!!! You guessed it on " << count << " time" << endl;
return 0;

}

Upvotes: 0

Views: 100

Answers (1)

eerorika
eerorika

Reputation: 238351

You can use std::uniform_real_distribution to generate random floating point:

std::random_device device;
std::mt19937 generator(device());
std::uniform_real_distribution<> distribution(least, greatest);
double a_random_number = distribution(generator);

I cant seem to find a way for those numbers to be with precision of 2 lets say.

Simply round the result to nearest value.

But be aware that typical floating point representations cannot precisely represent all decimal numbers such as 0.1 etc.

Upvotes: 1

Related Questions