Friday, July 31, 2009

Help !!what is the problem with this program? (C++)?

I am trying to write a program to give me the divitions of a number but it doesn't work!


can you find the problem?





#include%26lt;iostream.h%26gt;


#include%26lt;math.h%26gt;


#include%26lt;conio.h%26gt;


int main ()


{


clrscr ();


int a,b,m ;


float c;





cin%26gt;%26gt;a;


b=1;


while (a%26lt;b)


{


c=a%b;


if(c==0)


{


cout%26lt;%26lt;b;


cout%26lt;%26lt;"_";


}


++b;


}


getch();


}

Help !!what is the problem with this program? (C++)?
The problem is that your while statement is wrong. It should be a%26gt;b instead of a%26lt;b.





Second, you shouldn't declare all your variables at the top of your program. This is old C style. In C++, it's better to declare variables as close to where you use them as possible.





Third, you declare but never use m.





Fourth, c is declared as a float, but it should really be an int. But even better, get rid of it altogether. Just put a % b inside the if statement conditional.





instead of:


c = a%b


if (c==0)





just do:


if (a%b==0)





Edit: The above poster is wrong. Although c should not be declared as a float, the modulus operator will always return an integer value.
Reply:I've taken their examples and optimized your code to work with all types of compilers and cleaned up your code a bit.


Enjoy.





#include %26lt;iostream%26gt;


#include %26lt;math.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;windows.h%26gt;





using namespace std;





int main ()


{


system("cls");


int a,b;





cin %26gt;%26gt; a;





b = 1;





while (a %26gt; b)


{


if( a%b == 0 )


{


cout %26lt;%26lt; b %26lt;%26lt; "_";


}


++b;


}


getch();


}
Reply:I think you want the while line to say


while (a %26gt; b)


otherwise it exits immediately


No comments:

Post a Comment