0

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.

1 Answers1

4

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.

openTankist
  • 157
  • 1
  • 12
  • 1
    I forgot to paste stdio.h here. And, changing to lf worked. – da_vinci_3864 Sep 02 '21 at 08:27
  • 1
    @da_vinci_3864 It's a bit strange with floats and doubles.... For **double** and `scanf` you need `%lf`. For **float** and `scanf` you need `%f`. But for `printf` you can use `%f` for both double and float – Support Ukraine Sep 02 '21 at 08:29
  • 2
    @openTankist `%lf` is not needed for `printf` – Support Ukraine Sep 02 '21 at 08:30
  • @da_vinci_3864 Check the [manual for scanf](https://man7.org/linux/man-pages/man3/scanf.3.html), you can see that "`l` Indicates ... the next pointer is a pointer to double (rather than float)." – George Sep 02 '21 at 08:31
  • 1
    @4386427 It's not needed but considered good practice. The printf vs scanf inconsistency was fixed in C99. – Lundin Sep 02 '21 at 09:00