Monday, May 24, 2010

Computer Programming C++?

Guys i need halp with a code this is the assigment:





Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by an odd integer less than or equal to the square root of the number.)





This is what i got thanks to dhvrm here in yahoo





// test 1p.cpp : Defines the entry point for the console application.


//





#include "stdafx.h"


#include %26lt;iostream%26gt;


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





using namespace std;





int _tmain(int argc, _TCHAR* argv[])


{





int input;


int i;


float x;


bool z = true;





cout %26lt;%26lt; "Input a positive integer:" %26lt;%26lt; endl;


cin %26gt;%26gt; input;


x = sqrt(input);





if(input % 2 != 0)


{


for(i = 3; i %26lt;= x; i + 2)


}


if(input % i == 0)


{


z = false;


exit;


}





}


else {


z = false;


}





if(z == true)


{


cout %26lt;%26lt; input %26lt;%26lt; " is a prime number!" %26lt;%26lt; endl;


}


return 0;


}








But it does not compile i really need help is for a project.

Computer Programming C++?
#include %26lt;math.h%26gt;


#include %26lt;iostream%26gt;





bool isPrime(int num) {


int i;





if (num %26lt; 2) return false;


else if (num % 2 == 0)


return num == 2;





for (i = 3; i %26lt; num; i += 2)


if (num % i == 0) return false;





return true;


}





int main(int argc, char **argv) {


int input;





std::cout %26lt;%26lt; "Input a positive Integer: ";


std::cin %26gt;%26gt; input;





if (isPrime(input))


std::cout %26lt;%26lt; input %26lt;%26lt; " is a prime number." %26lt;%26lt; std::endl;


else


std::cout %26lt;%26lt; input %26lt;%26lt; " is not a prime number. " %26lt;%26lt; std::endl;





return 0;


}
Reply:You need to understand what the lines of code are doing....adding in comments might help. Until you do there is no way you'll get this program working.





Here are some areas that need investigating





if(input % 2 != 0)


{


// i +2 does nothing here....you need to make it i = i +2 if you want i to be incremented by 2


for(i = 3; i %26lt;= x; i + 2)


// where is the statement for the for loop eg


//for (;;;)


//{


//printf("statement goes here");


//}


}








} // %26lt;-- this doesnt match up with anything....count them


else {


z = false;


}





3) if its not compiling for you rewrite the main function as follows, as you're not using the argc/argv parameters.





int main(void)


{


}








There's possibly more needed to be done to get it to compile and run and then you'll have to sort out any logic errors.....but hopefully that will help you get there.





Good luck.
Reply:exit;


should be


exit(1);
Reply:What line is the error?


Send me a email - powellinthesouth@hotmail.com


No comments:

Post a Comment