compiling error

I'm a math student and learning from the book C++ for mathematicians.

The book separates interface from implementation. As I follow the book's instructions, I'm getting some errors.

There are two file, one is header file, gcd.h and the other gcd.cc. In gcd.cc, instead of "int main ()", the author prefers "long gcd (long a, long b){ " . When I run g++ gcd.cc it gives errors. On the other hand, if I switch to int main (), it yield the correct result. I'm using Ubuntu 14,04.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "gcd.h"
#include <iostream>
using namespace std;

long gcd(long a, long b){

  int a,b;
  cout << "Enter two numbers: " << endl;
  cin >> a >> b;

  // if a and b are both zero, print an error and return 0


  if ( (a==0) && (b==0) ) {
    cerr << "WARNING: gcd call with both argments equal to zero." << endl;
  
  return 0;
  }

  // Make sure a and b are both non-negative

  if (a<0) a = -a;
  if (b<0) b = -b;
  

  // if a is zero, the answer is b
  if (a==0) return b;
  if (b==0) return a;

  // iterative step

  long new_a = a;
  long new_b = b;

  while (b != 0) {
      new_a = b;
      new_b = a%b;

      a = new_a;
      b = new_b;
    }
 
  cout << a <<endl;
  return a;

}



And here is the header file, gcd,h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef GCD_H
#define GCD_H

/**
 * Calculate the greatest common divisor of two integers
 * Note: gcd(0,0) will return 0 and print an error message.
 * @param a the first integer
 * @param b the second integer
 * @return the greatest common divisor of a and b
 */

long gcd(long a, long b);

#endif
 
Last edited on
The gcd function is a function that you can call from other functions (main() if you want).

You are not supposed to read or print anything inside of gcd. Instead that would be something that you do before calling gcd.

1
2
3
4
5
6
7
int main()
{
	int a,b;
	cout << "Enter two numbers: " << endl;
	cin >> a >> b;
	cout << "The greatest common divisor of " << a << " and " << b << " is " << gcd(a, b) << ".\n";
}
Last edited on
Topic archived. No new replies allowed.