Hello. My program takes some preset numbers, for instance 20 to 30, then calculates for each number whether its proper divisors when added together, are less than, more than, or equal to the original number. It worked fine as a simple, run "only once and restart" program, but then I set it up using a "while loop" menu and found an unexpected behavior. The first time through, no matter which series of numbers I select, it works fine. Subsequent runs adds "10" to the desired numbers. For example, the first time through it checks 20, 21...30. The next time through, rather than rechecking 20-30, it now checks 31...32...to 41.
I tried using some flush commands at the end of suspect statements, but no luck there.
I would appreciate any help.
Code:
#include <iostream> // cout, cin, <<, >>
#include <iomanip> // maybe I will use this, maybe not.
#include <string> // string
#include <cstdlib> // exit()
using namespace std;
int sumOfDivisors(int getNum);
int x = 0;
int sum = 0;
int getNum = 0;
int main()
{
const string MENU =
"This program will check several series of numbers\n"
"to see if they are deficient, perfect or abundant.\n"
"Enter the appropriate key to check a particular series\n"
"of numbers.\n"
" a - 20 to 30;\n"
" b - 490 to 500;\n"
" c - 8120 to 8130;\n"
" q - to quit;\n"
"---> ";
cout << MENU;
char choice;
cin >> choice;
cout << "\n";
while (choice != 'q')
{
switch(choice)
{
case 'a':
getNum = 19 + x;
break;
case 'b':
getNum = 489 + x;
break;
case 'c':
getNum = 8119 + x;
break;
case 'q':
exit(1);
}
for (x = 0; x <= 10; ++x)
{
getNum++;
int sum = sumOfDivisors(getNum);
cout << "The sum of the divisors for "
<< getNum << " is: " << sum << "\n\n" << flush;
if (sum < getNum)
cout << "This number is deficient.\n\n"<< flush;
else if (sum == getNum)
cout << "This number is perfect!\n\n" << flush;
else
cout << "This number is abundant.\n\n" << flush;
cout << "The variable getNum now equals: " << getNum << "\n";
}
cout << "\n" << endl;
cout << MENU;
cin >> choice;
}
}
/*******************************************************************
* sumOfDivisors() calculates the number of divisors and adds them.
*
* Receive: getNum, an integer
* Returns: sum, an integer
*
* Modification history: added menu, March 2004. ---ALT
*********************************************************************/
sumOfDivisors(int getNum)
{
int pd = 2;
int sum = 1;
while (pd < getNum)
{
if (getNum % pd == 0)
sum = sum + pd;
pd++;
}
return sum;
}