2009-08-30 68 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

相關問題