Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Perfect, Abundant, Deficient program help (http://www.go4expert.com/forums/perfect-abundant-deficient-program-help-t22096/)

 Shoothy 13May2010 22:59

Perfect, Abundant, Deficient program help

I'm supposed to create a program that tells if the users inputted number is perfect a bundant defficient, but the answers are all coming out with big numbers (abundant everytime). Here's the code i have:

Code:

```#include<iostream> #include<string> using namespace std; int subP(int num){ int ans[1000]; for(int x=1;x<=num;x++){ double test = 0; test = num/x; if(test == int(num/x)){ ans[x]=test; } } cout<<endl; cout<<num<<endl; for(int y=0;y<=num;y++){ if(ans[y]=0){ cout<<y<<" "; } } int sum=0; for(int z=0;z<num;z++){ sum=sum+z; } return sum; } int main(){ Start: int num=1; int sum=0; cout<<"Type a number: "; cin>>num; if(num==0){ goto end; } sum = subP(num); cout<<endl<<sum; if(sum<num) cout<<endl<<"Deficient"; if(sum==num) cout<<endl<<"Perfect"; if(sum>num) cout<<endl<<"Abundant"; cout<<endl<<endl; goto Start; end: cout<<"the end"; }```

 Isaac Remuant 14May2010 07:11

Re: Perfect, Abundant, Deficient program help

You should indent your code and enclose it between CODE tags for better understanding.

Also, comments help a great deal. Especially if you're asking for help. If you don't comment your code you won't even be able to understand it after a brief period of time. Having to analyze one's own intentions makes you lose valuable time. So... Make it a habit.

For example. There's no explanation of what subP is supposed to be doing and it's name is not indicative (At least not for me) of it's purpose.
Code:

```int subP(int num){         int ans[1000];         for(int x=1;x<=num;x++){                 double test = 0;                 test = num/x;                 if(test == int(num/x)){                         ans[x]=test;                 }         } ....```
Now... Why did you hardcode 1000 for the array? Have you noticed what happens if you input a something bigger? You'll be out of bounds.

You either define a constant maximum somewhere so the user can't enter a higher value or you have a dynamic array instead of a static one.
Code:

`if(test == int(num/x))`
why is test a double and not an int?
Why do you typecase a int / int division? It will always return int. It will only return a floating point number if either one of it's elements is floating point.

The use of goto is a VERY VERY bad idea. Why did you use them instead of using loops?

I think you should explain what's your approach and how it's supposed to work. I don't get how you're trying to find if a number is perfect if you're not using the modulus to test if a number is a divisor.

 All times are GMT +5.5. The time now is 03:27.