I am working my way through the C++ without fear new edition, and have found some codes that dont work. This is a simple code to work out if a number is prime using the square root function and modulus. Here is the code as per the book:

The word double which is in red, is what I had to add to get past the errors stating that the compile was unsure if it was supposed to return a float double etc.

Now the next part of the exercise was to take the square root function out of the loop, and declare a new variable as the result of the square root of the users input, then get the function to check it if was a prime number, here is how far I got

I now get the error message error C2296: '%' : illegal, left operand has type 'float'. So how do I now complete this exercise, taking into account I am only on chapter 2 of the book

Code:

#include <iostream> #include <cmath> using namespace std; int main() { int n; int i; int isPrime = true; cout << "Please enter a number and press enter " ; cin >> n; cout << endl; i = 2; while (i <= sqrt(double(n)))// or (i*i<=n) { if (n % i == 0) isPrime = false; i++; } if (isPrime) cout << "Number is a prime number" << endl; else cout << "Number is not a prime number" << endl; }

Now the next part of the exercise was to take the square root function out of the loop, and declare a new variable as the result of the square root of the users input, then get the function to check it if was a prime number, here is how far I got

Code:

#include <iostream> #include <cmath> using namespace std; int main() { float m; int n; int i = 2; int isPrime = true; cout << "Please enter a number and press enter " ; cin >> n; cout << endl; m = sqrt (float (n)); cout << m; cout << endl; while (i <= m ) // or (i*i<=n) { if (m % i == 0) isPrime = false; break; } i++; if (isPrime) cout << "Number is a prime number" << endl; else cout << "Number is not a prime number" << endl; }

*Last edited by shabbir; 11Aug2011 at 13:26.. Reason: Code blocks*