Originally posted by moonwalker
your program crashes if you try to choose r > n
and do nPr
you should use an if condition to check this and prevent people from entering r > n.
I'm currently fixing that, and came across a lil' problem.
Basically, when you choose #3 on the main menu after the r > n error check (after it displays), the menu shows back up, and then you have to choose #3 again. Here's my new code
(at time of posting):
PHP Code:
#include "includes.h"
int pc; // Used for the choice between permutation, combination, or quiting
int n2; // n part of nCr and/or nPr
int r2; // r part of nCr and/or nPr
int ans; // The answer of permutations or combinations
unsigned long fact( unsigned long n );
unsigned long fact( unsigned long n )
{
if( n == 0 ) return 1;
else if( n <= 2 ) return n;
else return n * fact(n-1);
}
void s_p()
{
system("cls");
cout << " nPr = n! / (n-r)!\n"; // Formula definition
cout << " n = "; // N value
cin >> n2; // " " input
cout << " r = "; // R value
cin >> r2; // " " input
if(r2 > n2)
{
cout << "\n\n" << r2 << " > " << n2 << " doesn't factor out correctly!\n\n";
cout << "1) Go back to beginning\n"
" >> ";
cin >> ans;
if (ans = 1) { system("cls"); begin(); }
if (ans != 1) { system("PAUSE"); }
}
begin();
if(r2 <= n2)
{
permutation(fact(n2), fact(n2-r2)); // Figures the permutation
}
}
void s_c()
{
system("cls");
cout << " nCr = n! / (n-r)!r!\n";
cout << " n = ";
cin >> n2;
cout << " r = ";
cin >> r2;
if(r2 > n2)
{
cout << "\n\n" << r2 << " > " << n2 << " doesn't factor out correctly!\n\n";
cout << "1) Go back to beginning\n"
" >> ";
cin >> ans;
if (ans = 1) { system("cls"); begin(); }
if (ans != 1) { system("PAUSE"); }
}
if(r2 <= n2)
{
combination(fact(n2), fact(n2-r2));
}
}
void permutation(int n, int r)
{
ans = n / r;
cout << "\n\n" << ans << "\n\n";
system("PAUSE");
begin();
}
void combination(int n, int r)
{
ans = n / (r * fact(r2));
cout << "\n\n" << ans << "\n\n";
system("PAUSE");
begin();
}
void begin()
{
Start:
cout << " Permutation (1)\n"
" Combination (2)\n"
" Exit (3)\n\n";
cout << " ";
cin >> pc;
switch(pc)
{
case 1:
s_p();
break;
case 2:
s_c();
break;
case 3:
system("PAUSE");
break;
default:
cout << "\n" << pc << " is not a valid choice! Please choose another!\n\n";
system("PAUSE");
system("cls");
goto Start;
break;
}
}
I didn't change anything else.