C++ 頭文件中使用 sqrt、pow 等數學函數,以及結構體定義,缺少必要的標準庫頭文件包含,導致編譯錯誤。本文補全正確的頭文件結構。
struct point {
double x, y;
} // 缺少分號
double length(struct point a, struct point b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
// sqrt、pow 未聲明
}
#ifndef GEOMETRY_H
#define GEOMETRY_H
#include // sqrt, pow 等數學函數
#include // size_t 等
struct Point {
double x;
double y;
// 構造函數便於初始化
Point(double x_ = 0, double y_ = 0) : x(x_), y(y_) {}
};
// 使用 const 引用避免拷貝,inline 建議內聯
inline double distance(const Point& a, const Point& b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy); // 推薦用標準庫限定符
}
#endif // GEOMETRY_H
#include <cmath>:C++ 標準數學庫,提供 std::sqrt、std::pow 等};std::sqrt 避免污染全局命名空間#ifndef/#define/#endif 防止重複包含inline:頭文件中函數定義建議內聯Point),函數名 camelCase(distance)
#include "geometry.h"
#include
int main() {
Point p1(3, 4), p2(0, 0);
std::cout << "Distance: " << distance(p1, p2) << std::endl; // 輸出 5
return 0;
}