|
-
February 13th, 2012, 05:44 AM
#1
Prime Number Test
Hi
Got 2 errors
the program should let me enter number and check whether its a prime or not
Error 1 error C2668: 'sqrt' : ambiguous call to overloaded function c:\users\hani\test4\test4\code.cpp 15
Error 2 fatal error C1903: unable to recover from previous error(s); stopping compilation c:\users\hani\test4\test4\code.cpp 15
PHP Code:
# include <iostream>
# include <cmath>
using namespace std;
int main () {
int n;
int i;
int is_prime=true;
cout << " enter a number ";
cin >>n;
i = 2;
while ( i <= sqrt(n)) {
if ( n % i ==0)
is_prime = false;
i++;
}
if ( is_prime )
cout << " the number is prime "<<endl;
else
cout << " is not prime number "<<endl;
system ("PAUSE");
return 0;
}
-
February 13th, 2012, 08:01 AM
#2
Re: Prime Number Test
You are taking the sqrt of an int variable. The compiler does not know which overload
of sqrt to use (float ? double ?). You need to explicitly tell the compiler what to use:
Code:
while ( i <= sqrt( static_cast<double>(n) ) ) {
-
February 13th, 2012, 10:27 AM
#3
-
February 13th, 2012, 10:29 AM
#4
Re: Prime Number Test
As an aside, a very easy way to convert an int to a double is to add 0.0, for instance
Code:
while ( i <= sqrt( n + 0.0 ) ) {
-
February 14th, 2012, 07:41 AM
#5
Re: Prime Number Test
checked it lindley nice work
-
February 16th, 2012, 01:15 AM
#6
-
February 16th, 2012, 02:20 AM
#7
Re: Prime Number Test
should be
Code:
bool is_prime=true;
to avoid implicit conversions.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|