c++ - 简单的 C++ 错误 : "... undeclared (first use this function)"

标签 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;
}

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

您需要在main 之前进行前向声明:

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

您可以在 main 之前定义您的函数,这也可以解决问题:

#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() {
...
}

关于c++ - 简单的 C++ 错误 : "... undeclared (first use this function)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354522/

相关文章:

c++ - 带有实现的纯虚函数

c++ - 将 sleep() 注入(inject)到外部进程的函数中

c++ - 单元测试 native C++ 代码

c++ - 如何在Qt中的QGridLayout中设置QPushButton的大小

c++ - 动态规划/内存(计算三元组)

c++ - 有序集/ map 的计数功能

c++ - 在任意数据类型上使用 <algorithm> 库

C++ Integer 从 *char[] 中删除字符串

c++ - 删除复制构造函数会破坏继承的构造函数

c++ - 带有受歧视 union 和可选<>的奇怪段错误