尝试在没有 Math.h 的情况下计算以 10 为底的对数(非常接近)只是在连接函数时遇到问题

Trying to Calculate logarithm base 10 without Math.h (Really close) Just having problems with connecting functions

我正在尝试学习如何计算通过 scanf 输入到我的代码中的任何数字的以 10 为底的对数。我认为我可以计算 ln(a) a 作为数字输入。我有一个计算这个的工作代码;但是现在我只想将我的 ln(a) 代码输出的任何数字除以定义的 LN10。这是因为一个数的自然对数除以 10 的自然对数将输出我正在努力实现的所需的以 10 为底的对数值。这是我现在的烂摊子。非常感谢任何帮助!

#define _CRT_SECURE_NO_WARNINGS
#define ALMOSTZERO 0.0000000000000000001
#define LN10 2.3025850929940456840179914546844

#include <stdio.h>

double log10(double);
double ln(double);

void main()
{
    {
    double x, a;
    printf("Enter value: ");
    scanf("%lf", &x);
    while (x > 0)
    {
        double log10 = ln(x) * LN10;
        printf("log10(%lf)=%lf\n", x, a);
        printf("Enter value:  ");
        scanf("%lf", &x);
    }
    }
}

double ln(double x)
{
    double sum = 0.0;
    double xmlxpl = (x - 1) / (x + 1);
    double denom = 1.0;
    double frac = xmlxpl;
    double term = frac / denom;

    while (term > ALMOSTZERO)
    {
        sum += term;
        //generate next term
        denom += 2.0;
        frac = frac * xmlxpl * xmlxpl;
        term = frac / denom;
    }
    return 2.0 * sum;
}

您的代码中存在一些问题,但是您需要计算 log10 已编写函数来计算 ln 只是另一个简单的函数:

#define LN10 2.3025850929940456840179914546844

double log10( double x ) {
    return ln(x) / LN10;    
}

我也会更改您的 ln 函数,至少是停止迭代的条件,因为 term 可以变得足够小以至于 sum == sum + term(从数字上讲)。 在您的实际代码中,您可以提前停止,检查 abs(term) 相对于 sum 的值是否小于某个 epsilon。我只是用这个:

double ln(double x)
{
    double old_sum = 0.0;
    double xmlxpl = (x - 1) / (x + 1);
    double xmlxpl_2 = xmlxpl * xmlxpl;
    double denom = 1.0;
    double frac = xmlxpl;
    double term = frac;                 // denom start from 1.0
    double sum = term;

    while ( sum != old_sum )
    {
        old_sum = sum;
        denom += 2.0;
        frac *= xmlxpl_2;
        sum += frac / denom;
    }
    return 2.0 * sum;
}

这将为您节省一些迭代次数,从而为您的代码提供相同(近似)的结果。要处理最后一项,您应该采用其他一些数字策略。

你的主要也需要一些改变。至少对用户输入有更多的控制:

#include <stdio.h>

double log10(double);
double ln(double);

int main()
{
    double x, a;
    printf("This program calculates the logarithm base 10.\n");

    printf("Enter a positive value: ");
    while ( 1 == scanf("%lf", &x)  &&  x > 0.0)
    {
        double a = log10(x);
        printf("log10(%lf) = %.12lf\n", x, a);
        printf("Enter a positive value: ");
    }
    return 0;
}