What is '%f' and '%c' in C language? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is '%f' and '%c' in C language?

If the %c function converts letters to their ASCII equivalent, then in the following example why am I getting Z as output instead of it's ASCII number? https://code.sololearn.com/1621/#c Also, in line 11, if I change from %d to %f, I get 0.000000 as output. Shouldn't I be getting 42.000000 as the output? Thanking you in anticipation;

13th Dec 2018, 11:44 AM
Sanyog Jain
8 Answers
+ 4
%f expects a float, but you pass an int (a+b) and that doesn't work. You have to transform the result to a float, for example by writing a+(float)b, then it will work. %c expects a char and you pass the char 'Z', so 'Z' is what is printed.
13th Dec 2018, 11:57 AM
HonFu
HonFu - avatar
+ 4
"%f expects a float, but you pass an int (a+b) and that doesn't work." I'd like to emphasize (again) the importance of using a valid format specifier while reading from the input/writing to the output, because using an invalid (incompatible — integral vs. FP) specifier leads to UB. _____ https://en.cppreference.com/w/cpp/io/c/fprintf https://en.wikipedia.org/wiki/Undefined_behavior#Examples_in_C_and_C++
13th Dec 2018, 12:09 PM
Babak
Babak - avatar
+ 4
C++ Soldier (Babak), should I have written: 'We have no guarantee what will happen' (because with some compiler it MIGHT work)?
13th Dec 2018, 12:11 PM
HonFu
HonFu - avatar
+ 4
Haha yeah! Just be ready for new surprises! 8P
13th Dec 2018, 12:22 PM
Babak
Babak - avatar
+ 3
Yeah exactly. The same principles that we already discussed are applied to the above case, as well.
13th Dec 2018, 12:15 PM
Babak
Babak - avatar
+ 3
Okay, I see, thanks. The multitude of opportunities to create undefined behaviour is confusing when you're used to Python's peace of encapsulation, where every side step comes with an Error. ^^
13th Dec 2018, 12:19 PM
HonFu
HonFu - avatar
+ 2
You store it in your int c, right? c=(float) a+b? Then what happens is this: (float)a+b leads to a float value, but since you store it in an integer variable, it gets transformed right back to int. So either c has to be of float type or you have to write a+b directly in that printf statement.
14th Dec 2018, 9:32 AM
HonFu
HonFu - avatar
+ 1
@HonFu I wrote a+(float)b but still I am getting 0.000000 as output. What should I do to correct it?
14th Dec 2018, 9:25 AM
Sanyog Jain