-1

Consider:

#include <iostream>
using namespace std;

double convert(int knots)
{
    double mile;
    mile = knots * 6076 / 5280 / 60;
    return mile;
}

I am new to C++, and I am writing a very simple function that converts knots (int) to miles per minute (double). I wrote the above function and I got the following error.

collect2: error: ld returned 1 exit status

How can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zeyuxie
  • 65
  • 1
  • 7

1 Answers1

2

You probably have another error message before that line:

undefined reference to `main'

In order to build an executable program in C++ you need to declare the main function.

It is the main entry point to your program. Try this:

#include <iostream>
using namespace std;

double convert(int knots)
{
    double mile;
    mile = double(knots) * 6076 / 5280 / 60;
    return mile;
}


int main(void) {

    double miles = convert(10); // Use convert function
    cout << "Miles: " << miles << endl; // Print result
    return 0;
}

Note: You need at least one value to be explicitly cast to a double in order to use that operator/ version. See Why does dividing two int not yield the right value when assigned to double?.

And remember the associativity rules. An expression is resolved from left to right, so you only need to explicitly cast the first (or the second) operand in a multiple division/multiplication expression.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rama
  • 3,222
  • 2
  • 11
  • 26
  • 1
    *"In order to compile in c++ you need to declare the main function."* NO! you can compile any c++ source file. There is no need in `main` to compile c++ code. – Alex Lop. Apr 08 '17 at 18:56