Compiler used is CC of AIX. Below code shows the before and after difference.

$cat tst1.c
#include <stdio.h>
#include <math.h>

int main()
{
  int val1=nearest((double)(1.5)),val2=nearest((double)(2.5)),val3=nearest((double)(2.6));
  /*Before*/
  printf("nearest 1.5 ==> %d\n",val1);
  printf("nearest 2.5 ==> %d\n",val2);
  printf("nearest 2.6 ==> %d\n",val3);
  /*After*/
  printf("nearest 1.5 ==> %d\n",nearest((double)(1.5)));
  printf("nearest 2.5 ==> %d\n",nearest((double)(2.5)));
  printf("nearest 2.6 ==> %d\n",nearest((double)(2.6)));
  return 0;
}

$cc -c tst1.c
$cc tst1.o -o tst1 -lm
$./tst1
nearest 1.5 ==> 2
nearest 2.5 ==> 2
nearest 2.6 ==> 3
nearest 1.5 ==> 1073741824
nearest 2.5 ==> 1073741824
nearest 2.6 ==> 1074266112

Question is why does return value of nearest() have to be assigned to a variable to be printed correctly? I guess this concerns the static linking used, but couldn't figure out why.

有帮助吗?

解决方案

This is because nearest does not return an int. When you assign it to an int, C does the conversion, so printing it with the %d format is successful. When you call it, C leaves the value as is. That's why printing with %d fails the second time.

Adding an explicit cast will fix this problem:

/*After*/
printf("nearest 1.5 ==> %d\n",(int)nearest(1.5));
printf("nearest 2.5 ==> %d\n",(int)nearest(2.5));
printf("nearest 2.6 ==> %d\n",(int)nearest(2.6));

其他提示

Most probably nearest returns something else than int, so the format specification is incorrect the second time. Conversions between numeric types are implicit, so the assignment just works.

By the way, (double)1.5 is a superfluous cast, because literals containing decimal point default to double.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top