Type casting with printf statements on Mac OSX and Linux

I have a piece of code that behaves differently on Mac OSX and Linux (Ubuntu, Fedora, ...). This applies to type casting in arithmetic operations in printf reports. The code is compiled using gcc / g ++.

Following

#include <stdio.h>
int main () {
  float days = (float) (153*86400) / 86400.0;
  printf ("%f\n", days);
  float foo = days / 30.6;
  printf ("%d\n", (int) foo);
  printf ("%d\n", (int) (days / 30.6));
  return 0;
}

created on Linux

153.000000
5
4

and on mac osx

153.000000
5
5

Why?

To my surprise, this works on both Mac OSX and Linux.

printf ("%d\n", (int) (((float)(153 * 86400) / 86400.0) / 30.6));
printf ("%d\n", (int) (153 / 30.6));
printf ("%.16f\n",    (153 / 30.6));

Why? I have no clue. thanks.

+5
source share
10 answers

try the following:

#include <stdio.h>
int main () {
  float days = (float) (153*86400) / 86400.0;
  printf ("%f\n", days);
  float foo = days / 30.6;
  printf ("%d\n", (int) foo);
  printf ("%d\n", (int) (days / 30.6));
  printf ("%d\n", (int) (float)(days / 30.6));
  return 0;
}

Notice what is going on? The culprit is double floating point conversion. Remember that float is always converted to double in the varargs function. I'm not sure why poppy will be different. Better (or worse) IEEE arithmetic implementation?

+5

, - 32- float, double , , , - , , . " ", :

: " , , , ".

. , , IEEE 754, .

+4

days - , 5.0.

: , 5.0, int , int 5.

. , .

, , - , ( ) , .

+3

.

30.6 , IEEE 754, , , . , 5.0, , 4.

, , , . x87, 80- . , SSE2 ( Mac OS X), 128- , 4x32- 2x64-. . . GCC, , , -mfpmath.

+3

? , , . (int) ((float) (days / 30.6)) (int) (days / 30.6).

, , , .

, printf, :

#include <iostream>
int main () {
  float days = (float) (153*86400) / 86400.0;
  std::cout << days << std::endl;
  float foo = days / 30.6;
  std::cout << (int) foo << std::endl;
  std::cout << (int) (days / 30.6) << std::endl;
  return 0;
}

.

+1

Hmmmmmmm... , - - , Linux- 32- ( ?), Mac - 64- . 64- Linux .

+1

. , 30.6 IEEE. , "" .

- :

float days = (float) (153*86400) / 86400.0;

, , , , , , . ?

+1

float double, - Linux. MacOSX, , , MacOSX. Mac? PPC Intel?

, , , , . int, .

+1

, , :

#include <stdio.h>

int main(void)
{
    volatile double d_30_6 = 30.6;
    volatile float f_30_6 = 30.6;

    printf("%.16f\n", 153 / 30.6);   // compile-time
    printf("%.16f\n", 153 / d_30_6); // double precision
    printf("%.16f\n", 153 / f_30_6); // single precision

    return 0;
}

volatile , ...

+1

, , , ...


. ", , ?" .

", - , - , ? ..."

" ", - . ", ". . ", , - , , , - ?".

", , - ." , ...".

“Of course,” God said, “there are many opportunities to get people to sell their souls for another round of financing, eh?” He grinned. "So what did I mean?"

“Good,” Satan said, “I put my best demons on him.” They worked like a very devil to come up with something new, and I think they have it. call "floating point" ... "

0
source

All Articles