954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

code works with type unsigned long but not with type double

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;
}
freelancelote
Junior Poster in Training
89 posts since Aug 2008
Reputation Points: 34
Solved Threads: 2
 

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
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

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

freelancelote
Junior Poster in Training
89 posts since Aug 2008
Reputation Points: 34
Solved Threads: 2
 

There is double fmod(double,double) function in 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!

ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

Thanks ArkM, that solved it.

freelancelote
Junior Poster in Training
89 posts since Aug 2008
Reputation Points: 34
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You