Hpp-tiedosto:

 #ifndef CALCULATOR_H
#define CALCULATOR_H

#include <QObject>

class Calculator : public QObject
{
Q_OBJECT
public:
    explicit Calculator(QObject *parent = 0);

    void setAccuracy(double a);

    double Exponential(double x);
    double Sine(double x);
    double Cosine(double x);

private:
    double Power(double x, int n);
    double Factorial(int n);

    double accuracy;

signals:

public slots:

};

#endif // CALCULATOR_H

Cpp-tiedosto:

 #include "calculator.h"

Calculator::Calculator(QObject *parent) :
    QObject(parent)
{
    accuracy = 8;
}

void Calculator::setAccuracy(double a)
{
    accuracy = a;
}

double Calculator::Power(double x, int n)
{
    double y = x;

    for (; n > 1; n--)
        y *= x;

    return y;
}
double Calculator::Factorial(int n)
{
    double y = 1.0f;

    for (; n > 1; n--)
        y *= (float)n;

    return y;
}

double Calculator::Exponential(double x)
{
    int i;
    double y = 1 + x;

    for (i = 2; i < accuracy; i++) {
        y += 1 / Factorial(i) * Power(x, i);
    }

    return y;
}
double Calculator::Sine(double x) //y=x-1/3!*x^3+1/5!*x^5...
{
    int i, j;
    double y = x;

    for (i = 3, j = 0; i < accuracy; i += 2, j++) {
        if (j & 1)
            y += 1 / Factorial(i) * Power(x, i);
        else
            y -= 1 / Factorial(i) * Power(x, i);
    }

    return y;
}
double Calculator::Cosine(double x)
{
    int i, j;
    double y = 1;

    for (i = 2, j = 0; i < accuracy; i += 2, j++) {
        if (j & 1)
            y += 1 / Factorial(i) * Power(x, i);
        else
            y -= 1 / Factorial(i) * Power(x, i);
    }

    return y;
}
  • No labels
You must log in to comment.