乐闻世界logo
搜索文章和话题

Why does scanf() need "% lf " for doubles, when printf() is okay with just "% f "?

1个答案

1

This question involves the differences in how scanf() and printf() handle format strings when working with floating-point numbers in C. In C, double variables are typically used for double-precision floating-point numbers, while float variables are used for single-precision floating-point numbers.

For printf() function:

  • When using printf() to output floating-point numbers, both double and float types can be formatted with %f. This occurs because when a float variable is passed to printf(), it is automatically promoted to double type, as defined by the C standard's default argument promotion rules.
  • Therefore, even when passing a float variable to printf(), it is internally promoted to double, so using %f correctly prints the value.

For scanf() function:

  • Unlike printf(), scanf() requires knowing the exact type of the variable provided, as it needs to correctly populate input data into the specified variable. No automatic type promotion occurs here.
  • When inputting a double variable, you must use %lf to inform scanf() that the input should be stored as a double. If %f is used, scanf() expects a float pointer, causing type mismatch and potential runtime errors.
  • Using %lf ensures that user input is correctly interpreted and stored as double-precision floating-point numbers.

Example:

Consider the following code snippet:

c
#include <stdio.h> int main() { double num; printf("Please enter a double-precision floating-point number: "); scanf("%lf", &num); // Correct use of %lf to read double printf("You entered: %f\n", num); // %f can be used to print double return 0; }

In this example, using %lf ensures that scanf() correctly reads the user input into the double variable num. Then, %f is used in printf() to output the value, as printf() automatically handles double parameters.

In summary, this difference stems from how scanf() and printf() handle type promotion. For scanf(), the exact data type must be specified, whereas for printf(), type promotion makes %f sufficient.

2024年6月29日 12:07 回复

你的答案