You are here:

C++/Program not working

Advertisement


Question
hi,
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
{
randomize();
int rand;
rand = int(Lo + random(Hi - Lo));
return(rand);
}

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

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;

return(0);
}  

Answer
Vandan,
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,
Alan

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Alan F.

Expertise

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)!

Experience

I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2016 About.com. All rights reserved.