Even experienced C programmers make mistakes writing printf statements.
Let's look at a few mistakes. Try to figure out what's wrong with each of the
following printf statements. When you are finished, click on the button
below.
/* For these examples,
* time and total are integer variables, and
* root1 and root2 are floating point variables.
*/
printf("The current time is", time);
printf("The grand total is %f.\n", total)
printf("The roots are %f", root1, " and %f.\n", root2);
printf("At time %d, root1 = %f and root2 = %f\n", time, root1);
Click here for the answers.
When you write printf statements, the important things to remember are
these:
- Use ``%d'' to print integer values and use ``%f'' to
print floating point values. Don't mix them up!
- Make sure that you give the right number of arguments to
printf. Every ``%d'' must have a corresponding integer value, and
every ``%f'' must have a corresponding floating point value.
It would be nice if the C compiler would double-check your printf
statements for you, but unfortunately not all C compilers do. It's up to you
to follow the above rules.
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah