如何使用随机精度数字

时间:2018-10-08 15:10:36

标签: c++

您好,我需要编写程序的帮助。我试图弄清楚如何键入两个范围数字(一个是最大值,一个是最小值),程序将识别并输出其中一个之间的随机数。到目前为止,我已经弄清楚了,但它仅适用于整数,我似乎无法找到一种方法使这些数字具有2个可以说的精度。

#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;

}

1 个答案:

答案 0 :(得分:1)

您可以使用std::uniform_real_distribution生成随机浮点数:

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

我似乎找不到办法使这些数字具有2个精确度。

将结果四舍五入到最接近的值。

但是请注意,典型的浮点表示不能精确地表示所有十进制数字,例如0.1等。