I'm not sure that I calculated the numbers correctly, so if such a solution fits, please check it yourself, so that it would give you the numbers you need.
#include <iostream> #include <ctime> #include <cstdlib> int main() { srand(time(0)); double result; int celoe = 0, drobi = 0, znak = 0; char buff[10]; znak = rand() % 2; // 1 buff[0] = znak ? ' ' : '-'; if (buff[0] == '-') { // 2 celoe = rand() % 2; // Генерирует от 0 до 1 drobi = rand() % 236; // Генерирует от 0 до 235 sprintf(&buff[1], "%d.%d", celoe, drobi); // 4 } else { //3 celoe = rand() % 158; // Генерирует от 0 до 157 drobi = rand() % 457; // Генерирует от 0 до 456 sprintf(buff, "%d.%d", celoe, drobi); // 4 } result = atof(buff); // 5 std::cout << result << "\n"; // 6 system("pause"); return 0; }
- We generate a number from 0 to 1 which will determine the sign of the future fractional number.
- We check if our number is negative, then we generate values from a range of numbers that can be included in a negative fractional number.
- Well, if the number is positive, then for positive we generate numbers from the range you need.
- Here we create a string with a fractional number from the resulting numbers.
- We convert a string with a number into a double
- Display the result
PS People, if there is a simple way to generate fractional values, then unsubscribe, maybe it’s in vain that I’ve spent so much time on the city looking))
And you can make a separate function and when you call a function, transfer the necessary ranges and get the result.
#include <iostream> #include <ctime> #include <cstdlib> double generate(int min_celoe, int min_drobi, int max_celoe, int max_drobi) { double result; int celoe = 0, drobi = 0, znak = 0; char buff[10]; znak = rand() % 2; buff[0] = znak ? ' ' : '-'; if (buff[0] == '-') { celoe = rand() % (min_celoe + 1); drobi = rand() % (min_drobi + 1); sprintf(&buff[1], "%d.%d", celoe, drobi); } else { celoe = rand() % (max_celoe + 1); drobi = rand() % (max_drobi + 1); sprintf(buff, "%d.%d", celoe, drobi); } result = atof(buff); return result; } int main() { srand(time(0)); double results[100]; for (int i = 0; i < 100; i++) { results[i] = generate(1, 235, 157, 456); std::cout << results[i] << "\n"; } system("pause"); return 0; }