代碼就是這個樣子。注意:這是C++。
程序代码:
程序代码:
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include "tools.h"
struct Point
{
double X;
double Y;
double Z;
Point() : X(0), Y(0), Z(0) {};
std::string ToString(void)
{
char buffer[81];
sprintf_s(buffer, "X%-10.4f Y%-10.4f Z%-10.4f", X, Y, Z);
return std::string(buffer);
}
static double Distance(const Point& p1, const Point& p2)
{
return sqrt(pow(p2.X - p1.X, 2) + pow(p2.Y - p1.Y, 2) + pow(p2.Z - p1.Z, 2));
}
};
// 顯示程序使用幫助
void Show_Help(const std::string command_name)
{
printf_s("程序格式:\n");
printf_s("%s <輸入文件名> <輸出文件名>\n", command_name.c_str());
}
// 讀入文件數據
std::vector<Point> Load_Data(const char* filename)
{
std::vector<Point> data;
FILE* file;
if (fopen_s(&file, filename, "rt") == 0)
{
char buffer[1024];
Point point;
while (fgets(buffer, _countof(buffer), file) != NULL)
{
const char* p;
double x, y, z;
p = strchr(buffer, 'X');
if (p && (sscanf_s(p + 1, "%lf", &x) == 1))
{
point.X = x;
}
p = strchr(buffer, 'Y');
if (p && (sscanf_s(p + 1, "%lf", &y) == 1))
{
point.Y = y;
}
p = strchr(buffer, 'Z');
if (p && (sscanf_s(p + 1, "%lf", &z) == 1))
{
point.Z = z;
}
data.push_back(point);
}
fclose(file);
}
return data;
}
size_t Write_Data(const char* filename, std::vector<Point>& data)
{
size_t count = 0;
FILE* file;
if (fopen_s(&file, filename, "wt") == 0)
{
while (count < data.size() - 1)
{
fprintf_s(file, "%s\n", data[count].ToString().c_str());
double distance = Point::Distance(data[count + 1], data[count]);
if ( distance > 0.1)
{
Point next_point = data[count];
const int n = static_cast<int>(distance / 0.1);
const double increase_x = (data[count + 1].X - data[count].X) / n;
const double increase_y = (data[count + 1].Y - data[count].Y) / n;
const double increase_z = (data[count + 1].Z - data[count].Z) / n;
for (int i = 0; i < n - 1; ++i)
{
next_point.X += increase_x;
next_point.Y += increase_y;
next_point.Z += increase_z;
fprintf_s(file, "%s\n", next_point.ToString().c_str());
}
}
++count;
}
fprintf_s(file, "%s\n", data[count].ToString().c_str());
fclose(file);
}
return count;
}
// 程序主入口
int main(int argc, char* argv[])
{
if (argc < 3)
{
Show_Help(GetJustFileName(argv[0]));
Pause();
return EXIT_FAILURE;
}
std::vector<Point> data = Load_Data(argv[1]);
printf_s("輸出記錄總數: %u\n", Write_Data(argv[2], data));
return EXIT_SUCCESS;
}

授人以渔,不授人以鱼。



