Thread: recursion and inaccurate results

  1. #1
    Registered User divineleft's Avatar
    Join Date
    Jul 2006
    Posts
    158

    recursion and inaccurate results

    I just made a fraction simplifying program, and everything works except for one thing. When I run the program the first time, the answers are exact. But, when I recurse the main() function I get an answer that is close, but maybe off by a couple decimal places. This has happened to me with other programs before and I was just wondering what the cause of this was.

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    vector<int>toping;
    vector<int>bottoming;
    
    	
    void process (int number, vector<int> &which)
    {
    	for (int index = 1; index <= number; ++index)
    	{
    		if (number%index == 0)
    		{
    			which.push_back(number/index);
    		}					
    	}
    }
    
    int compare (int top, int bottom)
    {
    	for (int index = 0; index < toping.size(); ++index)
    	{
    		for (int endex = 0; endex < bottoming.size(); ++endex)
    		{
    			if (toping[index] == bottoming[endex])
    			{
    				return bottoming[endex];
    			}
    		}
    	}
    	cout << "Error: Compare" << endl;
    }
    
    int main()
    {
    	int top = 0, bottom = 0, common = 0;
    	int newtop = 0, newbottom = 0, flag = 0;
    	char again;
    
    	cout << "Numerator: ";
    	cin >> top;
    	if (top == 0)
    	{
    		return 0;
    	}
    	else if (top < 0)
    	{
    		top = top * -1;
    	}
    
    	cout << "Denominator: ";
    	cin >> bottom;
    	cout << endl;
    	if (bottom == 0)
    	{
    		return 0;
    	}
    	else if (bottom < 0)
    	{
    		bottom = bottom * -1;
    	}
    
    	process(top, toping);
    	process(bottom, bottoming);
    	common = compare(top, bottom);
    	newtop = top / common;
    	newbottom = bottom / common;
    	
    	cout << '\t' << newtop << " / " << newbottom << endl << endl;
    	if (common == 1)
    	{
    		cout << "Fraction is in lowest terms." << endl;
    	}
    	else if (common > 1)
    	{
    		cout << "The GCF is " << common << endl;
    	}
    
    	cin >> again;
    	main(); // recurse main program
    	return 0;
    }

  2. #2
    Registered User divineleft's Avatar
    Join Date
    Jul 2006
    Posts
    158
    Nevermind, I solved my own problem. Haha, forgot to clear the vectors. Sorry...

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    You can't recurse main in C++. This is only allowable in C. You should use a loop:
    Code:
    do {
    	int top = 0, bottom = 0, common = 0;
    .
    .
    	cin >> again;
    } while (again != 'n');

  4. #4
    Registered User divineleft's Avatar
    Join Date
    Jul 2006
    Posts
    158
    Good to know, thanks.

Popular pages Recent additions subscribe to a feed