Scanf and float with scientific notation
In this article, now let’s do one exercise.
Exercise:
Find out the Number of electrons responsible for producing the given charge. Use scientific notation while inputting and outputting the numbers.
The equation is, Number of electrons = given charge/charge of an Electron.
First of all, let me create some variables. Let me use a data type double to take Charge. And after that, to take charge of an electron, let me create one more variable chargeE. Then, calculate the number of electrons. For that, let me create one more variable double electrons.
After that, let me use printf to give the message “Enter the charge,” and then, let’s scan the number. For that, I’m going to use %lf (for double, you have to use lf) and &charge.
After that printf, let’s ask the user to “Enter the charge of an electron.” And let me take this number in scientific notation. For that, I am going to use scanf(“%le”,&chargeE);. The code is shown in Figure 1.
After that, let’s calculate the number of electrons.
electrons = (charge /chargeE) * -1;
The given charge is divided by the charge of a single electron, which would give you the negative result, so let me multiply by -1.
And let’s print the result in scientific notation. The total number of electrons = %le\n, and let’s print electrons here. And also, let me print in non-scientific notation. For that, let me use %lf. The code is shown in Figure 2.
Now let’s see how this goes. Let’s compile this code and execute the binary as a command-line application.
Here I Enter the charge as 0.005 and Enter the charge of an electron as -1.602e-19. You can input the number in scientific notation, so let me input -1.602e-19.
These are the outputs shown in Figure 3. The first output is in scientific notation, and the second output is in non-scientific notation.
That’s about the usage of float and double data types in ‘C.’
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1