You are passing extra parameters to printf
. scanf
doesn't support format specifiers the way you have done it. Perhaps your goal is to accept floating point numbers only upto a certain precision, for which you can refer here but it is messy and I don't see a scenario where one needs to do it. Also, you should check the return value of scanf
to see if your input has been read and assigned to variables. You can read more about it in its man
page. It basically returns the number of values successfully read. I suspect you are using some old compiler like TurboC but you should learn to code as per the latest standards. As for why your answers are 0.0, the computation is being casted to int so you can either use 1.0/2*m*v*v
or cast it explicity (float)1/2*m*v*v
.
Here is what the correct code would be like
#include <stdio.h>
int main(void)
{
float m, v, kinetic_energy;
printf("Enter mass and velocity: ");
/* always validate EVERY user-input, especially numeric conversions */
if (scanf ("%f", &m) != 1) { /* validate input for m */
fputs ("error: invalid floating point input.\n", stderr);
return 1;
}
if (scanf ("%f", &v) != 1) { /* ditto for v */
fputs ("error: invalid floating point input.\n", stderr);
return 1;
}
printf("With m = %0.1f kg and v = %0.1f m/s,\n", m, v);
kinetic_energy = (float)1 / 2 * m * v * v; /* compute energy */
printf("the kinetic energy is found to be %0.2f J.", kinetic_energy);
return 0;
}
PS: fputs
here, is used to dump error messages, which should be kept separate from the general program output(stdout)
to stderr
as a good practice.