in Programming in C
1,019 views
0 votes
0 votes
printf("%d",20/3.2); or printf("%i",20.0/3);     or %u     // why does it prints garbage value

Could someone explain(or provide info) about format specifiers %d, %s, %f.... in detail in C
in Programming in C
1.0k views

2 Answers

3 votes
3 votes
C language is meant for writing high performance code and one is expected to write codes with proper meaning. It is not having error supporting feature like Java -- which makes it less robust but it can run much faster. Now coming to the question, C mandates that if we use any format specifier in printf and pass a different type as the corresponding argument, behaviour is undefined. i.e., if "%d" is used, passed value must be an integer (char is also of type integer). Here, 20/3.2 returns a double value because "3.2" is double and for any operation, the result will be of the largest type involved in the operation. 20/3 would give correct answer of 6. Otherwise use an explicit type casting with (int) (20/3.2)
by
1 vote
1 vote

%s  $\Rightarrow$ sequence of characters.

 For reading and printing, integer values using scanf() and printf() function, either %i or %d is used but there is a subtle difference in both %i and %d format specifier.

%d specifies signed decimal integer while %i specifies integer.

while using scanf()

%d always takes base 10

%i auto detects the base means it can take octal, decimal or octal numbers. For octal input just write 0 with the input number like 012 and for hexa values put 0x like 0x12.

%d and %i behave similar with printf

https://ide.geeksforgeeks.org/C68BEND7Hl