C – Read Float using Scanf()
To read a float value entered by user via standard input in C language, use scanf() function.
scanf() reads input from stdin(standard input), according to the given format and stores the data in the given arguments.
So, to read a float number from console, give the format and argument to scanf() function as shown in the following code snippet.
float n; scanf("%f", n);
Here, %f
is the format to read a float value and this float value is stored in variable n
.
Examples
In the following example, we read a float value input by the user in standard input to a variable n
using scanf() function.
main.c
#include <stdio.h> int main() { float n; printf("Enter a float value : "); //read input from user to "n" scanf("%f", &n); //print to console printf("You entered %f\n", n); return 0; }
Output
Enter a float value : 3.14 You entered 3.140000 Program ended with exit code: 0
Enter a float value : -1.414 You entered -1.414000 Program ended with exit code: 0
ADVERTISEMENT
Conclusion
In this C Tutorial, we learned how to read a float value entered by user via standard input using scanf() function.