Hi,
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?

thanks

My code is:

#include<iostream.h>
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;
			do
			{
				cout<< i<< ", ";
				division= target/i;
				target= division;
				mod= target % i;
				
			}
			while (mod == 0);
			
		}
	}
		

	cout<< endl;
	return 0;
}

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!

Thanks ArkM, that solved it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.