Hey everyone, I'm new to the forums here, and also new to C++ and hoping to get some help. In my code, I want a random number to be displayed but in between two numbers. (ex. with my code, it generates a huge random number in the thousands, I only want it to be between 1 - 20) Here is my code:

//declaring header files
#include "stdafx.h"
#include <iostream>

//using the std namespace for easier writing
using namespace std;

//initializing the main program
int main()
//main code
{
	//display weclome message
	cout << "Hello, and welcome number adding system!\n\n";
	//press any key to continue and skip a line
	system("PAUSE");
	cout << endl;
	//loop the random number
	int cin_int = 0;
	while(cin_int < 1)
	{
		int rand_int = rand();
		system("PAUSE");
		cout << endl;

	}
	


}

Hey everyone, I'm new to the forums here, and also new to C++ and hoping to get some help. In my code, I want a random number to be displayed but in between two numbers. (ex. with my code, it generates a huge random number in the thousands, I only want it to be between 1 - 20) Here is my code:

//declaring header files
#include "stdafx.h"
#include <iostream>

//using the std namespace for easier writing
using namespace std;

//initializing the main program
int main()
//main code
{
	//display weclome message
	cout << "Hello, and welcome number adding system!\n\n";
	//press any key to continue and skip a line
	system("PAUSE");
	cout << endl;
	//loop the random number
	int cin_int = 0;
	while(cin_int < 1)
	{
		int rand_int = rand();
		system("PAUSE");
		cout << endl;

	}
	


}

Change line 21 to:

int rand_int = rand() % 20 + 1;

On a side note, your while loop from lines 19 to 25 is an infinite loop. cin_int never changes, so once inside the loop, you'll never get out. You're also not currently displaying the number in this code. You're just outputting a blank line.

This article has been dead for over six months. Start a new discussion instead.