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

tyo*_*ooo 2 c logarithm calculator

我正在尝试学习如何计算我通过 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;
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*b__ 5

您的代码中存在一些问题,但是您在编写了计算数字的ln的函数后计算log 10所需的只是另一个简单的函数:

#define LN10 2.3025850929940456840179914546844

double log10( double x ) {
    return ln(x) / LN10;    
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

这将为您节省一些迭代,给出与您的代码相同(近似)的结果。为了处理最后一项,您应该采用其他一些数字策略。

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

#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;
}
Run Code Online (Sandbox Code Playgroud)