Home > Software design >  When I input my data the program is not able to detect my data and it doesnt give me the output
When I input my data the program is not able to detect my data and it doesnt give me the output

Time:05-02

#include <stdio.h>

void main (void) {

float m, v, kinetic_energy;



printf("Enter mass and velocity: ", m, v);
scanf("%.1f", &m);
scanf("%.1f", &v);

printf("With m = %.1f kg and v = %.1f m/s,\n", m, v);
    
kinetic_energy = 1/2*m*v*v;

printf("the kinetic energy is found to be %.2f J.", kinetic_energy);

} When i run my programme i cant seem to get my output and instead the data shown is 0.0

CodePudding user response:

Change void main (void) to int main(void).

Remove , m, v from printf("Enter mass and velocity: ", m, v);.

In the scanf calls, change %.1f to %f.

In kinetic_energy = 1/2*m*v*v;, 1/2 divides the int 1 by the int 2 and produces an int result which is truncated, so it is 0. Change the expression to use floating-point constants, not integer constants.

CodePudding user response:

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. 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: ");
  scanf("%f", &m);
  scanf("%f", &v);

  printf("With m = %0.1f kg and v = %0.1f m/s,\n", m, v);
    
  kinetic_energy = (float)1/2*m*v*v;

  printf("the kinetic energy is found to be %0.2f J.", kinetic_energy);
  return 0;
}
  •  Tags:  
  • c
  • Related