Program does not work.

Hi, I'm trying to make a program that finds and states all the perfect numbers in a given range, but for some reason my code isn't working.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  #include <iostream>


int ifReturnPerfectOrZero(int iX)
{
    int iSum = 0;
    for (int iChecker = 1; iChecker < iX ; ++iChecker)
    {
        if (iX%iChecker == 0)
        {
            iSum = iSum + iChecker;
        }

        if (iX == iSum)
        {
            return iX;
        }
    }

    return 0;
}

int main()
{
    std::cout << "Enter limit (from zero to)" << std::endl;
    int iLim = 0;
    int Passer = 0;
    std::cin >> iLim;
    int iaPerfectNums[50];

    for (int iX = 1; iX < iLim; ++iX)
    {
        Passer = ifReturnPerfectOrZero[iX];
        iaPerfectNums[(iX-1)] = Passer;
    }
    
    std::cout << "The perfect numbers in the given range are:"
    
    
    for (int iNum = 0; iNum < iLim; ++ iNum)
    {
        if(iaPerfectNums[iNum] != 0)
        {
            std::cout << iaPerfectNums[iNums] << std::endl;
        }
    }

}


Basically, what it does is it first asks for the limit, then checks each number from 1 to LIM if its a perfect number (a number that is equal to the sum of its divisors), if it is it adds it to iaArray, if its not it just adds in 0 to the array. When it reaches the LIM, it checks all of iaArrays values, if its a 0, it doesn't do anything, if its anything other than zero, it couts it.

Thanks.
What input did you put in, what output did you get out, and what did you expect to get out?
I inputted 100 and I got this:
6
6
6
24
24
24
24
24
24
24
24
28
28
28
28
28
28
28
28
28
28



But I expected this:

6
28

I have no idea where the 24 is coming from, the function should only have 6 and 28 as valid return values....
Just tried, this works
Try to simplify your solution as much as possible
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int isperfect(int n){
	int sum = 0;
	for(int i = 1; i <= n/2;i++)
		if(n % i == 0)
			sum+=i;
	if(sum == n)
		return 1; // true
	else
		return 0; // false
}

int main ()
{  
      cout << "Enter max num : ";
      int max = 0;
      cin >> max;
      for (int i = 1; i < max; ++i)
      	if(isperfect(i))
      		cout << i << '\n';
}

You can make return data type of isperfect() bool.
The question says finds and states all perfect numbers in given range so I didn't store it in an array. :p
Last edited on
Topic archived. No new replies allowed.