2009-08-30 67 views
3

嘿家伙,我正在为我的第一个C++程序的学校工作。出于某种原因,我收到以下错误,当我尝试编译:简单的C++错误:“...未申报(首次使用此功能)”

`truncate' undeclared (first use this function) 

全部来源:

#include <iostream> 
#include <math.h> 

using namespace std; 

#define CENTIMETERS_IN_INCH 2.54 
#define POUNDS_IN_KILOGRAM 2.2 

int main() { 
    double feet, inches, centimeters, weight_in_kg, weight_in_lbs; 

    // get height in feet and inches 
    cout << "Enter height (feet): "; 
    cin >> feet; 
    cout << "Enter (inches): "; 
    cin >> inches; 

    // convert feet and inches into centimeters 
    centimeters = ((12 * feet) + inches) * CENTIMETERS_IN_INCH; 

    // round 2 decimal places and truncate 
    centimeters = truncate(centimeters); 

    printf("Someone that is %g' %g\" would be %g cm tall", feet, inches, centimeters); 

    // weights for bmi of 18.5 
    weight_in_kg = truncate(18.5 * centimeters); 
    weight_in_lbs = round(weight_in_kg * POUNDS_IN_KILOGRAM); 

    printf("18.5 BMI would correspond to about %g kg or %g lbs", weight_in_kg, weight_in_lbs); 

    // weights for bmi of 25 
    weight_in_kg = truncate(25 * centimeters); 
    weight_in_lbs = round(weight_in_kg * POUNDS_IN_KILOGRAM); 

    printf("25.0 BMI would correspond to about %g kg or %g lbs", weight_in_kg, weight_in_lbs); 

    // pause output 
    cin >> feet; 

    return 0; 
} 

// round result 
double round(double d) { 
    return floor(d + 0.5); 
} 

// round and truncate to 1 decimal place 
double truncate(double d) { 
    return round(double * 10)/10; 
} 

任何帮助,将不胜感激。谢谢。

回答

10

您需要提前声明您main前:

double truncate(double d); 
double round(double d); 

你可能之前主要定义功能,这将解决过的问题:

#include <iostream> 
#include <math.h> 

using namespace std; 

#define CENTIMETERS_IN_INCH 2.54 
#define POUNDS_IN_KILOGRAM 2.2 

// round result 
double round(double d) { 
    return floor(d + 0.5); 
} 

// round and truncate to 1 decimal place 
double truncate(double d) { 
    return round(double * 10)/10; 
} 

int main() { 
... 
} 
+0

我做了第二个解决方案,但我得到同样的错误呢! –

3

您正试图在调用一个函数truncate()

centimeters = truncate(centimeters); 

你还没有告诉编译器的功能是什么,所以它是未定义,编译器所反对。

在C++中,所有函数在使用之前都必须声明(或定义)。如果您认为您使用的是标准C++库函数,则需要包含其头文件。如果您不确定您是否使用C++库函数,则需要声明并定义您自己的函数。

请注意,在基于POSIX的系统上,truncate()是一个截断现有文件的系统调用;它将有一个不同于你正在尝试使用的原型。


再往下,你的代码 - 隐藏关滚动条的底部 - 是truncate()round()函数定义。将函数定义放在文件的顶部,以便编译器在使用之前知道它们的签名。或者在文件顶部添加函数的前向声明,并保留它们所在的位置。

2

您需要在使用前声明函数他们。将truncateround的定义移到main函数之上应该能够做到。

+0

或者只是提供声明,就像AraK说的那样。 – a2800276

+0

感谢您的帮助。这解决了这个问题。 – Pooch

相关问题