0

该程序是在我们的书中编写的,我们被告知要用 C 和 C++ 编译它,尽管它对两者都不起作用。下面的错误是当我尝试以 .cpp 格式编译它时

第一个错误:LNK2019:函数“int __cdecl evennumber(int)”(?evennumber@@YAHH@Z) 中引用的未解析的外部符号“long __cdecl oddnumber(short)”(?oddnumber@@YAJF@Z) 第二个错误:LNK1120: 1 未解决的外部问题

// This program shows function and variable declarations and their scopes.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//#include<iostream.h>
int keven = 0, kodd = 0;
long evennumber(short);
long oddnumber(short);
int even(int);
int evennumber(int a) {
    // genuine declaration
    if (a == 2) {
        printf("keven = %d, kodd = %d\n", keven, kodd);
        return keven;
    }
    else {
        a = (int) a / 2;
        if (even(a)) {
            // Is a even?
            keven++;
            return evennumber(a);
        }
        else {
            kodd++;
            return oddnumber(a);
        }
    }
    // return a;
}
int oddnumber(int b) {
    // genuine declaration
    if (b == 1) {
        printf("keven = %d, kodd = %d\n", keven, kodd);
        return kodd;
    }
    else {
        b = 3 * b + 1;
        if (!even(b)){
            //Isbodd?
            kodd++;
            return oddnumber(b);
        }
        else {
            keven++;
            return evennumber(b);
        }
    }
    // return b;
}
int even(int x) {
    // % is modulo operator.
    return ((x % 2 == 0) ? 1 : 0);
}
void main() {
    register short r = 0;   // a register type variable is faster,
    int i = r;  // it is often used for loop variable
    float f;
    for (r = 0; r < 3; r++) {
        printf("Please enter an integer number that is >= 2\n");
        scanf("%d", &i);

        if (even(i))
            f = evennumber(i);
        else
            f = oddnumber(i);
    }
}
4

1 回答 1

1

链接器表明您声明了一个符号long evennumber(short);,但找不到定义。首先检查你的函数的签名:声明和定义必须匹配!例如,我认为您想改为声明int oddnumber(int)

请小心,以防您定义多个具有相同名称但签名不同的函数。这在 C++ 中是允许的,但在 C 中是不允许的。

于 2013-10-22T10:27:11.297 回答