#include <stdio.h>
int main()
{
signed char ch;
ch = 128;
printf("%f", ch);
return 0;
}
Can anyone explain why it is printing 0.000 every time??
I tried %f
as a format specifier for signed char value.
#include <stdio.h>
int main()
{
signed char ch;
ch = 128;
printf("%f", ch);
return 0;
}
Can anyone explain why it is printing 0.000 every time??
I tried %f
as a format specifier for signed char value.
If you want to print a value, that you have in an integer variable, as if it were floating point, you have to write an explicit cast.
#include <stdio.h>
int main()
{
signed char ch;
ch = 128;
printf("%f\n", (double)ch);
return 0;
}
In a call to most functions that take a double
or float
argument, the compiler would insert this cast for you, but it doesn't do it for printf
because printf's argument list isn't declared. See the older question I just linked this one to, for more detail.
Since you know the value is an integer, you can also write out the fractional part yourself:
#include <stdio.h>
int main()
{
signed char ch;
ch = 128;
printf("%d.000000\n", ch);
return 0;
}
will print the same thing as the first example.
To print the value of signed char
you need to use %d
format. %f
id to use float
and double
types.
#include <stdio.h>
int main()
{
signed char ch;
ch = 128;
printf("%d\n", ch);
return 0;
}
https://godbolt.org/z/5816GvPWd
It will output -128
as you set the last bit of 8-bit integer (assuming CHAR_BIT == 8) and the system uses two's complement integers
Assignment of 128 to 8-bit signed char
is implementation-defined as 128 cannot be accommodated in 8 bit integer. Most implementations will behave as I wrote above - ie print -128