好的,所以我有一个我的 Trig 类,我用它来存储一个静态值表,以便在我的程序中更快地执行 sin、cos 和 tan 函数。是否可以对我当前的方法进行任何评论和/或速度改进?多亏了以前的答案,我已经感觉自己对 C++ 更有能力了。
三角函数
#pragma once
#include <math.h>
class Trig
{
private:
struct Table
{
static const int multiple = 10; // Accurately stores values to 1/10 of a degree
double sin[360*multiple];
Table();
};
static const Table table;
static void shrinkRange(double*); // Shrinks degrees to range 0-359 for proper array indexing
public:
static double sin(double);
static double cos(double);
static double tan(double);
};
触发.cpp
#include "Trig.h"
Trig::Table::Table() // table constructor
{
double const PI = 3.14159265358979323;
double const degToRad = PI/180.0;
double const incr = 1.0/multiple;
int index = 0;
for (double angle = 0; index != 360*table.multiple; angle += incr)
Table::sin[index++] = _INC_MATH::sin(angle*degToRad);
}
Trig::Table const Trig::table; // initialize static table member
void Trig::shrinkRange(double* degrees)
{
if (*degrees >= 360)
*degrees -= 360*( (int)*degrees/360);
if (*degrees < 0)
*degrees += 360*( -(int)*degrees/360 + 1);
}
double Trig::sin(double degrees)
{
shrinkRange(°rees);
degrees *= table.multiple;
return Trig::table.sin[(int)(degrees+0.5)];
}
double Trig::cos(double degrees)
{
return Trig::sin(degrees + 90);
}
double Trig::tan(double degrees)
{
return Trig::sin(degrees)/Trig::cos(degrees);
}