I am using
#include<conio.h>
#include<stdlib.h>
to generate a random number from 1-10.
the code is:
rando = rand() % 10 + 1;
for some reason 2 keep being generated. Is there something wrong with my phrasing?
I am using
#include<conio.h>
#include<stdlib.h>
to generate a random number from 1-10.
the code is:
rando = rand() % 10 + 1;
for some reason 2 keep being generated. Is there something wrong with my phrasing?
 
    
    To generate random nuber from 1 to 10, you should really use rand() % 10 + 1
but firstly needed initialization of random seed, look at example:
  #include <stdio.h>      /* printf, NULL */
  #include <stdlib.h>     /* srand, rand */
  #include <time.h> 
  int iSecret ;
  /* initialize random seed: */
  srand (time(NULL));
  /* generate secret number between 1 and 10: */
  iSecret = rand() % 10 + 1;
If you're using C++ 11 you can consider using <random> header (you also have to seed the random engine):
#include <random>
std::random_device rd;
std::default_random_engine dre(rd());
std::uniform_int_distribution<int> uid(1,10);
int number = uid(dre);
 
    
    1) You shouldn't use rand(), it has bad distribution, short period etc...
2) You shouldn't use %x when MaxValue % x != 0 because you mess your uniform distribution (suppose you don't use rand()), e.g. 32767 % 10 = 7 so number 0-7 are more likely to get
Watch this for more info: Going native 2013 - Stephan T. Lavavej - rand() Considered Harmful
You should use something like:
#include <random>
std::random_device rdev;
std::mt19937 rgen(rdev());
std::uniform_int_distribution<int> idist(0,10); //(inclusive, inclusive) 
I in my codes use something like this:
template <typename T>
T Math::randomFrom(const T min, const T max)
{
    static std::random_device rdev;
    static std::default_random_engine re(rdev());
    typedef typename std::conditional<
        std::is_floating_point<T>::value,
        std::uniform_real_distribution<T>,
        std::uniform_int_distribution<T>>::type dist_type;
    dist_type uni(min, max);
    return static_cast<T>(uni(re));
}
NOTE: the implementation is not thread safe and constructs a distribution for every call. That's inefficient. But you can modify it for your needs.
 
    
    Your problem is that you didn't initialize the seed for rand(), i.e. you didn't call srand() (in the usual old form of srand(time(NULL))), so you get the same number sequence.
But, anyway, you should not use rand() in C++11 and newer.
You may want to use std::mt19937 and std::uniform_int_distribution instead.
You may want to read this answer for more details.
(I'm not going to duplicate the code and answer text here).