error C2668: 'sqrt' : ambiguous call to overloaded function

i am teaching myself how to use C++ and i keep getting this error and i am not sure what the error means can some one help this is my code the error is in line 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Prime1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

int main() {
	int n;	//Number to test for prime-ness
	int i;	//Loop counter
	int is_prime = true;	//Boolean flag...
							//Assume true for now
	//Get a number from the keyboard
	cout << "Enter a number and press ENTER: ";
	cin >> n;
	// Test for a prime by checking for divisibility
	// by all whole numbers from 2 to sqrt(n)
	i = 2;
	while (i <= sqrt(n)) {	//While i is <= sqrt(n),
		if (n % i == 0)		//If i divides n,
			is_prime = false;	// n is not prime.
		i++;	//add 1 to i
	}
	// Print results
	if (is_prime)
		cout << "Number is prime." << endl;
	else
		cout << "Number is not prime." << endl;
	system ("PAUSE");
	return 0;
}
Last edited on
The reason it is telling you this is because there are 2 overloaded functions for sqrt, which can either take a double, or a float. The compiler does not know which one you want to use here.

Changing it to
while (i <= sqrt((double)n)) { //While i is <= sqrt(n),
or
while (i <= sqrt((float)n)) { //While i is <= sqrt(n),

Will fix the problem.
Last edited on
awesome thank you for the info i will make sure to add that to the memory bank for next time
There is sqrt(int) in standard C++ now, hopefully Visual Studio will update its <cmath> soon.
Last edited on
Topic archived. No new replies allowed.