Solrik
Solrik

Reputation: 49

Double turns into nan in C

I have a function that uses an int, say 2488, to store temperature values. I have to call a function getTemp() to get the int. The getTemp function returns a double and uses the int to return the correct number. All the getTemp() does is return (double)x / 100.0 where x is 2488 in this case.

The returned double is then 24.88. This value then is sent to another function that adds the double to an array. Function is called DAaddDouble(double m, int x, int y) where m is the value to add, x and y is the coordinates that specify where to add the double.

Problem is, it turns into nan.

double a = getTemp();
//a is correct, i.e. 24.88
DAaddDouble(a, x, y);
/*-----------inside DAaddDouble----------*/
void DAaddDouble(double m, int x, int y)
{
   //at this point, a (or m, same) is 0.nan
   cord = x + y*40; //where to put the double
   snprintf(DARRAY[cord], 5, "%f",m);
   printf(....DARRAY[cord]...);

}

output: -nan

Upvotes: 0

Views: 1425

Answers (3)

mcleod_ideafix
mcleod_ideafix

Reputation: 11418

How do you know m is NAN. If you have infered by the value "printed" to DARRAY[cord], take into account that the format string should be "%lf" and not "%f".

void DAaddDouble(double m, int x, int y)
{
   //at this point, a (or m, same) is 0.nan
   cord = x + y*40; //where to put the double
   snprintf(DARRAY[cord], 5, "%f",m); /* should be "%lf" for printing doubles */
   printf(....DARRAY[cord]...);

}

Upvotes: 0

chux
chux

Reputation: 153338

Mis-match prototype.

Usage of DAaddDouble() is not preceded by its declaration/definition, thus the compiler assumes the function is:

int DAaddDouble(int m, int x, int y);

Precede the usage of DAaddDouble() by the function definition or a function prototype.

void DAaddDouble(double m, int x, int y);

A good compiler will warn of this. Insure all warning are enabled.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

The signature of function DAaddDouble is:

void DAaddDouble(int m, int x, int y)

Note that m is of type int, and inside the function, you have:

snprintf(DARRAY[cord], 5, "%f",m);

in which %f expects type double, it's undefined behavior.

Probably what you need is to have the parameter m as double(as in your words above the code).

void DAaddDouble(double m, int x, int y)

Upvotes: 1

Related Questions