Problems in Recursion

I am trying to input the two numbers in order to find the GCD of a and b using Recursion. (with decimals of 4 digits should be included). There is an error in it especially in return gcd(b, a % b); which says main.cpp:9:18: error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%’ and error: ‘setprecision’ was not declared in this scope
I need help with this code.

// C++ program to find GCD of two numbers 
#include <iostream> 
using namespace std; 
// Recursive function to return gcd of a and b 
double gcd(double a, double b) 
{ 
	if (b == 0) 
		return a; 
	return gcd(b, a % b); 
	
} 

// Driver program to test above function 
int main() 
{ 
	double a, b;
	cout<<"Enter the first number"<<endl;
	cin>>a;
	cout<<"Enter the second number"<<endl;
	cin>>b;
	
	cout<<fixed<<setprecision(4)<<"The GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b); 
	return 0; 
}
Last edited on
¿how do you define modulo for floating point numbers? ¿what's 3.14 % 2.79?

for setprecision() you need to #include <iomanip>
It makes no sense to talk about the GCD of floating-point numbers (doubles). a and b should be of type int in both main() and function.

For setprecision you need to include the header <iomanip> ... only you shouldn't need it because gcd of floating-point numbers makes no sense.
fmod() but gcd is still going to be weird.
C++17 has std::gcd() - but only for ints. https://en.cppreference.com/w/cpp/numeric/gcd
Topic archived. No new replies allowed.