Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf specify integer format string for float

Tags:

c

casting

printf

#include <stdio.h>

int main()
{
    float a = 5;
    printf("%d", a);
    return 0;
}

This gives the output:

0

Why is the output zero?

like image 393
amit singh Avatar asked Oct 27 '09 16:10

amit singh


1 Answers

It doesn't print 5 because the compiler does not know to automatically cast to an integer. You need to do (int)a yourself.

That is to say,

#include<stdio.h>
void main()
{
float a=5;
printf("%d",(int)a);
}

correctly outputs 5.

Compare that program with

#include<stdio.h>
void print_int(int x)
{
printf("%d\n", x);
}
void main()
{
float a=5;
print_int(a);
}

where the compiler directly knows to cast the float to an int, due to the declaration of print_int.

like image 96
Mark Rushakoff Avatar answered Sep 19 '22 12:09

Mark Rushakoff