You are here:

C++/Program not working


Can you please tell me what is wrong with my code and how i can fix it. It is not generating the proper random number and not displaying the name properly. Compiler: the one that comes with a guide to programming C++ by lawrenceville press. Here's my code:

#include <iostream.h>
#include <lvp\string.h>
#include <lvp\random.h>

void Signature()
// Displays a Declaration of Authorship
// Pre: Enter a Name
// Post: Displays the Name
String Name;
cout << "This program was written by " << Name << endl;

int RandomInRange(int Lo, int Hi)
// Returns a random number in range Lo...Hi
// Pre: Enter the range
// Post: Displays a random number in between the range
int rand;
rand = int(Lo + random(Hi - Lo));

int main()
String Name;
cout << "Enter your name: ";
getline(cin, Name);

cout << endl;

int low, high;

cout << "Enter a low number for the range: ";
cin >> low;
cout << "Enter a high number for the range: ";
cin >> high;

RandomInRange(low, high);

cout << endl;

cout << "A random number in between " << low << " and " << high << " is: ";
cout << rand << endl;


If I'm reading this right there are a couple problems. Your random function that takes two numbers as input is fine. However, when you call this function in the main part of the program, you don't do anything with its' returned value. I.E. This line of code:
RandomInRange(low, high);
Doesn't do anything by itself. You have to declare the variable 'rand' as an 'int' type variable when you're declaring the high and low variables. Then you would do this:
rand = RandomInRange(low, high);
That way the value that the RandomInRange function comes up with is saved in the main portion of the program, and you can use the 'rand' value later on. I hope this solves the problem that you were having. If you were having another problem that isn't what I discussed, please let me know.

Best Of Luck,


All Answers

Answers by Expert:

Ask Experts


Alan F.


Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!


I have a C++ web page that discuses the basics of C++. The address is:

©2016 All rights reserved.