Question for sqrt

Hi guys,

I was doing some practice for testing the prime number and I used the 'sqrt' command but my compiler showed an error. I'm not sure why. I was wondering if you guys could give me some advice.

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
#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 << "Number is prime." << endl;
	else
		cout << "Number is not prime." << endl;

	return 0;
}


I changed the 'i' to float but that didn't work either. I'm very new to C++.
Define variables n and i as float.
I defined the variables n,i as float but now its saying that the % has an error.

Error message output is : error C2296: '%' : illegal, left operand has type 'float'.

(I'm using Visual C++ 2010 express.)
I have not seen that you are using %.

Then return type int to the variables and use sqrt( ( float ) n )

the % operator will not work because it the modulus operator applies to Integer division only - a float is not an int.

% (modulus) is used to get the remainder - something int's need but floats do not (floats have decimals remember? those represent the remainder)
Topic archived. No new replies allowed.