Reputation: 1046
I have two char string and they have '-' and '+' sign.
I want to pick a random sign from a variable. So far i tried like this, but it outputs only '+' - sign, how can i make it correct?
srand(time(0));
char rand_symb;
char plus = '+';
char minus = '-';
rand_symb = rand() % (plus - minus + 1) + minus;
Upvotes: 2
Views: 1100
Reputation: 76235
You're choosing between two values, so you need to generate two random values. It's simplest to just generate 0 and 1:
int value = rand() % 2;
(Yes, rabid purists will tell you that this is doomed, because rand()
sucks, but it's good enough for what you're currently doing).
Based on that value, pick one of the two characters:
char ch = value ? '+' : '-';
or, to make the whole thing more compact:
char ch = rand() % 2 ? '+' : '-'.
Upvotes: 2
Reputation: 43662
You'd better off using C++11 random generation facilities with a fair coin simulator
#include <iostream>
#include <random>
int main()
{
std::random_device r;
std::default_random_engine e1(r());
std::bernoulli_distribution coin_flip(0.5);
bool sign = coin_flip(e1);
std::cout << (sign ? '-' : '+');
}
Upvotes: 5