+ 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;
8 ответов
+ 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.
+ 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++
+ 4
C++ Soldier (Babak), should I have written: 'We have no guarantee what will happen' (because with some compiler it MIGHT work)?
+ 4
Haha yeah! Just be ready for new surprises! 8P
+ 3
Yeah exactly. The same principles that we already discussed are applied to the above case, as well.
+ 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. ^^
+ 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.
+ 1
@HonFu I wrote a+(float)b but still I am getting 0.000000 as output.
What should I do to correct it?