C Programming Code for Bullet Energy Calculation

A couple of C programs that I wrote that do the exact same thing, but are coded a bit different. They both calculate the energy of a bullet. You have to input the weight in grains and the velocity in feet per second. I am learning how to program in C and wanted to try new things.

The first one uses a struct and has some functions. The second one is much simpler and just has one main function. They both should compile with any C compiler.

#include <stdio.h>

struct bullet
{
  double fps;
  double grains;
  double energy;
};

//function declarations
void read(struct bullet *);
void write(struct bullet);

int main()
{
  struct bullet b;

  //keep looping for multiple calculations
  while(1)
  {
    read(&b);
    if(b.grains == 0)
    {
      break;
    }
    //calculate energy and convert to proper units
    b.energy = (.00000444 * b.fps * b.fps * b.grains)/2;
    write(b);
  }
  return(0);
}

void read(struct bullet *b)
{
  printf("Bullet Grains(Enter 0 to exit): ");
  fflush(stdout); //some systems do not print line without newline character unless you use this to force it to print
  scanf("%lf", &(*b).grains);
  if((*b).grains == 0)
  {
    printf("Exiting\n");;
  }
  else
  {
    printf("Feet per sec: ");
    fflush(stdout);
    scanf("%lf", &b->fps);
  }
}

void write(struct bullet b)
{
  printf("\nEnergy in Ft-Lbs: %.1lf\n\n", b.energy);
  fflush(stdout);
}
#include <stdio.h>

int main()
{
  double fps;
  double grains;
  double energy;

  //keep looping for multiple calculations
  while(1)
  {
    printf("Bullet Grains(Enter 0 to exit): ");
    fflush(stdout); //some systems do not print line without newline character unless you use this to force it to print
    scanf("%lf", &grains);
    if(grains == 0)
    {
      break;
    }
    printf("Feet per sec: ");
    fflush(stdout);
    scanf("%lf", &fps);

    //calculate energy and convert to proper units
    energy = (.00000444 * fps * fps * grains)/2;
    printf("\nEnergy in Ft-Lbs: %.1lf\n\n", energy);
    fflush(stdout);
  }
  return(0);
}


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *