1

I made a very simple code which calculates the values of a function:

#define MIN 0.00001
#define MAX 1
#define MAXP 10000


 double func_log(double x)
{
    double r=RPWN;
printf(" MAXP = %e  \n",MAXP);
printf(" MIN = %e  \n",MIN);
printf(" MAX = %e  \n",MAX);

    double y;
    if (x>r || x==0) return(0.0);
    else {
        y = r+((r*r)/(2.*x)-x/2.)*log((1+r/x)/(r/x-1));  
    }
    return y;       

}

That fonction is in a file.c which is compiled with other source files. The problem is that MAXP cannot be set to its value. Here is what I get when I ask to print out the values of MIN, MAXP, and MAXP:

 MAXP = 4.940656e-324  
 MIN = 1.000000e-05  
 MAX = 1.000000e+00

I really don't understand why I get 4.940656e-324 for MAXP, I never had such issue. Also when I write #define MAXP 10000., I then get MAXP = 1.000000e+04. I compile with gcc, does someone has any clue?

Digvijaysinh Gohil
  • 1,367
  • 2
  • 15
  • 30
pulsar_hh
  • 125
  • 2
  • 9
  • 1
    MAX and MAXP are integer constants being printed as doubles. Happiness is not one of the options. Add decimal points to the definitions. – Jonathan Leffler Nov 23 '17 at 15:14
  • Enable compiler warnings. Voting to close this as simple typo. – Lundin Nov 23 '17 at 15:14
  • 1
    @Lundin not necessarily a typo, the question is OK. For a beginner this behaviour may actually look strange – Jabberwocky Nov 23 '17 at 15:16
  • @MichaelWalz Fine, then close as duplicate to [What Are Integer Literal Type?](https://stackoverflow.com/questions/41405578/what-are-integer-literal-type-and-how-they-are-strored). – Lundin Nov 23 '17 at 15:30
  • @Lundin not close enough for me. And the OP will probably not understand – Jabberwocky Nov 23 '17 at 15:40

2 Answers2

3

The problem is not in the value of MAXP, but in the format specifier %e that you are using to print it.

MAXP is not a variable, it is a macro. Hence, it has no type associated with it. The compiler figures out the type of 1000 from the context, which in case of printf means int (the default interpretation of 1000). In a different context 1000 could be interpreted as a float or a double, e.g. float f = MAXP; An important thing to remember is that MAXP is textually replaced with 1000 in the body of your code.

If you want MAXP to be interpreted as a double by default, add .0 at the end:

#define MAXP 10000.0

If you want it to remain an integer literal, use %d to print it

printf(" MAXP = %d  \n", MAXP);

or add an explicit cast:

printf(" MAXP = %e  \n", (double)MAXP);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    In fact, you don't even need the `0` at the end (in case there is some possibility of it being mistaken by the programmer as a significant figure), you just need the decimal point or an exponent part. – Ian Abbott Nov 23 '17 at 15:18
2

The problem is that %e prints float and double types, but your MAXP and MAX type integer.

You can use %d to print integers.

Bastian
  • 10,403
  • 1
  • 31
  • 40