HELP WITH RAND and FACTORIALS PLEASE

closed account (ENb7ko23)
I am trying to create a simple menu where option 1, squares an integer, option 2 finds the factorial, option 3 gives you a random number and option 9 exits the program. So far all of it works except for two problems:
1) I get the same random number every time I use it and
2) whenever I type in an integer to find the factorial (after choosing option two)the programs just ends after I hit enter. Please help me! I cannot figure out what I am doing wrong. Thanks a lot, much appreciated. Here is what I have:

P.S. I am sorry about the code layout I am new to this site.

#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
int choice;
int i,r;
int integer;
int result;
int factorial(int n);

srand (time(0));
r = rand();

int factorial(int integer);

do
{
cout << "Please select the function desired and press Enter: ";
cout << "\n\n";
cout << " 1) Square the number provided.\n";
cout << " 2) Factorial the number provided.\n";
cout << " 3) I just need a random number.\n";
cout << "\n";
cout << " 9) Exit program, please.\n";
cout << "Your selection:\n";
cin >> choice;
cout << "\n";

switch (choice)
{

case 1:
cout << "Please enter an integer number:\n";
cin >> integer;
result = pow(integer,2);
cout << integer << " squared is " << result;
cout << "\n";

break;
case 2:
cout << "Please enter an integer number:\n";
cin >> integer;

{
int product = 1;
while (integer > 0)
{
product = integer * product;
integer--;
}

return product;
}

cout << "Factorial is " << integer;
break;
case 3:
cout << " Random number: " << r;
cout << "\n";
break;
case 9:
cout << " End of Program.\n";
break;
default:
cout << "Not a valid choice.\n";
cout << "Choose again.\n";
}
}while (choice != 9);

return(0);
}
Last edited on
P.S. I am sorry about the code layout I am new to this site.
put the code inside code tags [code][/code].
closed account (ENb7ko23)
i did it didnt do anything
Please do NOT double post:
http://www.cplusplus.com/forum/general/59757/
And don't try saying 'sorry' either, there is NO EXCUSE.
srand (time(0));
r = rand();

will give u a similar random number or the same one every single time because it is based off of your system clock (as in operating system not processor). You will need to come up with a way to vary this number. You could do something like;

rannum = (rand()%scheme)+1;

where the scheme is a number of your choice as if you are looking for a number in between two other numbers or this could be user chosen.

And, your question regarding why your program ends after you hit enter, look closely in your code for this. It is pretty obvious, if you can't figure out throw a goto in there!

There are many ways of doing random numbers and there is no right way, google it.
Topic archived. No new replies allowed.