尝试在没有Math.h的情况下计算对数基数10(真正关闭)只是在连接函数时遇到问题

时间:2016-03-13 10:08:44

标签: c calculator logarithm

我正在尝试学习如何计算通过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;
}

1 个答案:

答案 0 :(得分:3)

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

#define LN10 2.3025850929940456840179914546844

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

我也改变了你的ln函数,至少是停止迭代的条件,因为term可以变得足够sum == sum + term(数字上说)。 在您的实际代码中,您可以提前停止,检查abs(term)是否小于某个epsilon相对于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;
}

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

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

#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;
}