Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
I wrote this piece of code for generating a random binary number with two for loop like the following:

C++
<pre>srand(time(0));
	for (i = 1; i <= 11; i++)                                                               
	{                                                                                       
		buffer.push_back(i);
	}
	for (i = 1; i <= buffer.size(); i++)
	{
		buffer[i] = rand() % 2;
		std::cout << buffer[i] % 2 << " ";
	}
	std::cout << std::endl;



there are 2 problems :
1) when I replace it in the proper place in my whole code, the compiler(in visual studio 2017) give me a warning about this line: srand(time(0)); that (Warning C4244 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data)

2)how I can decrease the number of for loop to have just one for loop?

What I have tried:

<pre lang="c++">
srand(time(0));
	for (i = 1; i <= 11; i++)                                                               
	{                                                                                       
		buffer.push_back(i);
	}
	for (i = 1; i <= buffer.size(); i++)
	{
		buffer[i] = rand() % 2;
		std::cout << buffer[i] % 2 << " ";
	}
	std::cout << std::endl;
Posted
Updated 22-Apr-18 10:15am

The type conversion warning is normal and can be supressed. Why dont you write it in one loop?
C++
srand((unsigned int) time(0));

for (i = 1; i <= 11; i++)                                                               
{                                                                                       
	buffer.push_back(i);

	buffer[i] = rand() % 2;
	std::cout << buffer[i] << " ";// giving the result out ???
}
 
Share this answer
 
Comments
MK2266 22-Apr-18 14:35pm    
could you please also solve an error that exists in my written code?
Why are you taking the modulus of two twice? Actually, why do it at all? Usually the way rand is used is you define a range for your values and write it as
C++
value = rand() % maxValue;
Then values will have a range of zero to maxValue. In the "what you have tried section", the first loop only serves the purpose of initializing the vector. This could be written as :
for( i = 0; i < valueCount; ++i )
{
    int value = rand() % maxValue;
    buffer.push_back( value );
}
You need to define the variables valueCount and maxValue to make this usable. The return of rand will range from 0 to RAND_MAX. You can initialize the vector to a given size with reserve(). If you know how many you are going to have that can be a good idea. Mostly for large numbers so there no reallocations.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900