Page 1 of 1

Compile error, can someone have a look?

Posted: Sun Jan 29, 2006 9:25 pm
by Laputa
I am moving from Java to C++ and this code gives error, please tell me where is the error:

Code: Select all

#include<iostream>
using namespace std;
int rank[1000000];

void main()
{
	long a, b, c;

	while (cin>>a>>b)
	{
		//Calculate & Track for max
		int max = 0;
		for (int i = a; i <= b; i++)
		{
			if (rank[i] == 0)
				rank[i] = findrank(i);
			if (max < rank[i])
				max = rank[i];
		}
		//Print out
		cout << max;
	}
}

int findrank(int& x)
{
	int rank, next;
	if (x == 1)
	{
		rank = 0;
	}
	else
	{
		if (x % 2 == 0)
			next = x/2;
		else
			next = x*3+1;

		if (next > 1000000 || rank[next] == 0)
			rank = 1 + findrank[next];
		else
			rank = 1 + rank[next];
	}

	if (x < 1000001)
		rank[x] = rank;

	return rank;
}

Posted: Mon Jan 30, 2006 4:26 am
by Cho

Code: Select all

rank = 1 + rank[next];
It can't be compiled even in your local machine, right?

Posted: Mon Jan 30, 2006 4:31 am
by neno_uci
Here are your errors according to my compiler(g++):

Code: Select all

laputa.cc:5: error: `main' must return `int'
laputa.cc: In function `int main(...)':
laputa.cc:16: error: `findrank' undeclared (first use this function)
laputa.cc:16: error: (Each undeclared identifier is reported only once for each function it appears in.)
laputa.cc: In function `int findrank(int&)':
laputa.cc:26: error: `int findrank(int&)' used prior to declaration
laputa.cc:39: error: invalid types `int[int]' for array subscript
laputa.cc:40: error: pointer to a function used in arithmetic
laputa.cc:40: error: pointer to a function used in arithmetic
laputa.cc:40: error: invalid conversion from `int (*)(int&)' to `int'
laputa.cc:42: error: invalid types `int[int]' for array subscript
laputa.cc:46: error: invalid types `int[int]' for array subscript

Posted: Mon Jan 30, 2006 6:46 am
by chunyi81
Your rank array is declared in main function and you are trying to access it in your findrank function. Just like in Java, you cannot access another method's local variables. Maybe you would like to describe what you intended to do with this code?

Posted: Mon Jan 30, 2006 9:27 pm
by Laputa
It's my very first try to the 3n+1 problem. I see that I should move the rank arrays into the beginning of the class. Is there anything else I need to fix?

Posted: Tue Jan 31, 2006 5:00 am
by chunyi81
Did you read neno_uci's post?

Fix those errors as well as the one I pointed out.

Posted: Thu Feb 02, 2006 7:04 am
by Laputa
Thank you for all trying. I bring the code up to my tutor and he helped me fixed it. By the way, I know that the code is wrong already. I just didn't know how to fix it. The compiler told me I had these errors already.