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

最后都变了- 提交于 2019-12-06 11:32:48

There are some issues in your code, but what you need to calculate the log10 having written the function to calculate the ln of a number is just another simple function:

#define LN10 2.3025850929940456840179914546844

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

I'd change your ln function too, at least the condition to stop the iterations, becuase term can become little enough that sum == sum + term (numerically speaking). In your actual code you can stop earlier, checking that abs(term) be less then some epsilon relative to the value of sum. I simply used this:

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

This will save you some iterations giving the same (approximated) result of your code. To take care of the last terms you should adopt some other numeric strategy.

Your main needs some changes too. At least more control of the user input:

#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!