Search code examples
clogarithm

The function log(x) in C is always giving the same value


Basically, I am trying to find the logarithm of a number using the log(x) function in the math.h library of C. But, for any and every value that I enter for the variable x, I end up with the same answer: -722.259365. Where is the problem with my code below?

I am kind of new to C, so please don't mind if this is too silly a mistake.

#include<stdlib.h>
#include<math.h>
void PrintLogarithm(double x){
    if(x<=0){
        printf("Positive numbers only please.\n");
        return;
    }
    double Result = log(x);
    printf("%f\n", Result);
}
int main(){
    double x;
    scanf("%f", &x);
    PrintLogarithm(x);
    return 0;
}

I am kind of new to C, so please don't mind if this is too silly a mistake.


Solution

  • First of all, you are missing an include

    #include <stdio.h>
    

    Secondly, you are not using the correct format specifier. You are using doubles, so you should use %lf. If you compile with the -Wformat flag, your compiler will warn you about this by telling you something like this:

    /cplayground/code.cpp:16:17: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
        scanf("%f", &x);
               ~~   ^~
               %lf
    

    If you fix these 2 problems, your program should finally work as expected.

    #include <stdlib.h>
    #include <math.h>
    #include <stdio.h>
    
    void PrintLogarithm(double x) {
        if(x<=0) {
            printf("Positive numbers only please.\n");
            return;
        }
    
        double Result = log(x);
        printf("%lf\n", Result);
    }
    
    int main() {
        double x;
        scanf("%lf", &x);
    
        PrintLogarithm(x);
    
        return 0;
    }
    

    Edit : As commenters pointed out, printf() works fine with either %lf or %f as the format specifier.