Why is a float rounded down to C when converting to int?

In an interview, they asked me what I think about the following code:

#include <stdio.h>

int main()
{
    float f = 10.7;
    int a;
    a = f;
    printf ("%d\n", a);
}

I answered:

  • The compiler generates a warning when changing floatto intwithout translation.

  • int will matter as garbage, because you are not using a cast.

Then they allowed me to run the program in an online compiler. I was stunned. Both of my assumptions were wrong. The compiler did not give any warnings, but inthad a value of 10. Even when I changed the value floatto a value equal to 10.9 or 10.3, the answer was the same. Even if put castdid not change the result.

Can someone tell me why this happens and in what cases the result will be different.

: gcc.


EDIT: , , 10. - , ? - float int ? ?

-1
5

, 6.3.1.4 :

, _Bool, (.. ). , undefined.

undefined . , , , undefined.

int ,

int , .

"", - C, ( - , ). , .

float-to-int . , .

GCC , , -Wconversion -Wfloat-conversion. , .

+9

C:

  • ,
  • void *,
  • ( )
  • -const- const,

, , , double x = 1 / 2;. , .

. gcc , -Wall -Wextra -Wconversion -Wfloat-conversion clang : clang -Wall -Weverything. , gcc, , , - . : Makefile, gcc c89 c99.

, , , , :

float f = 10.7;
printf("%d\n", f);

, f printf double, printf int %d. , (int). , , .

, , undefined, :

char x = 300;
int x = 1e99;

, .

, , :

double f = 10000000000000;
char a = f;
float f = d;
int i = d;

, , undefined . , , .

, ​​ 0, , , round() 0.5 , , .

+2

.

C, , . a 10. , C , C.

0

C , , - , , .

, , , ( ) 0,5 , , , , , t , 0.5 .

, C , , .

0

I think your reasoning makes sense. C, however, usually does not make any sense; floating point values ​​are implicitly rounded to zero. You can force the compiler to issue a warning when types are implicitly converted in this way.

/*test.c*/

#include <stdio.h>

int main()
{
    double f;
    int a;

    f = 10.7;
    a = f;
    printf("%d\n", a);
    return 0;
}

With GCC, the option we are looking for is -Wconversion:

$ c89 -pedantic -Wall -Wconversion test.c
test.c: In function β€˜main’:
test.c:9:6: warning: conversion to β€˜int’ from β€˜double’ may alter its value [-Wfloat-conversion]
  a = f;
      ^
-3
source

Source: https://habr.com/ru/post/1628538/


All Articles