2

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; 
6
  • 2
    it is unclear what are you asking. Commented Nov 18, 2016 at 15:41
  • 1
    Why not use the ternary operator? en.wikipedia.org/wiki/%3F: Commented Nov 18, 2016 at 15:42
  • 2
    Something like rand_symb = "+-"[rand() % 2]; Commented Nov 18, 2016 at 15:44
  • 4
    Your formula using %(plus-minus)+minus only works if plus and minus are adjacent in the ascii table and minus comes before plus. Both assumptions are wrong. Commented Nov 18, 2016 at 15:44
  • 1
    rand_symb = rand() % (plus - minus + 1) + minus; sorry, but this looks like cargo cult programming to me Commented Nov 18, 2016 at 15:46

2 Answers 2

5

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 ? '-' : '+'); } 

Example

Sign up to request clarification or add additional context in comments.

Comments

2

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 ? '+' : '-'. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.