I'm learning c++ at the moment and the problem I have is probably very simple.
I wrote some code to calculate prime factors of a given number.
If I define variables as unsigned long, the code compiles and the program runs. If I define variables as double then compiler throws error.
Any help?


My code is:

int main()

	unsigned long target;
	unsigned long i;
	unsigned long module;
	unsigned long division;
	cout << "enter a number: ";
	cin >> target;
	for (i=2; i<=target; i++)
		module= target % i;
		if (module == 0)
			unsigned long mod;
				cout<< i<< ", ";
				division= target/i;
				target= division;
				mod= target % i;
			while (mod == 0);

	cout<< endl;
	return 0;
8 Years
Discussion Span
Last Post by freelancelote

study your math operators more closely.
read the compiler error - it should be telling you something useful, as well as pointing out the offending line.

Bet it's this one: module= target % i; Why doesn't the compiler like doubles there?


vmanes, you are wright. Errors are in lines 15 and 24 and it says:
invalid operands of types 'double' and 'double' to binary 'operator%'
Does it mean I can calculate modulus of type double?
If it does... any ideas on how to go around this?
Thank you


There is double fmod(double,double) function in <math.h> header. It calculates so called floating-point remainder of its arguments. At first sight it's a true equivalent of the operator % defined only for integral types arguments. In actual fact a floating-point remainder is not so well-defined function as a modulo operator for integers.

By definition floating point numbers are not exact values. Sometimes you may get very strange results, for example:

cout << fmod(1.0,0.1) << endl;
// printed 0.1, not (expected) 0.
cout << fmod(2e20+1,2.0) << endl;
// printed 0, not (expected) 1...

That's why operator % does not defined for double and float (approximate) values: fmod is not the same math operator as % for integral types!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.