Calculate GPS cordinates at a specific time - c

I have problem I'm sitting with.
For example, suppose someone runs in straight lines and at constant speed between the positions on the left side of Table 1. The time they reach each position is shown next to the position. They stopped running at time 11. If the GPS records a position every 2 units of time, its readings would be the records on the right side of Table 1.
input:
The input consists of a single test case. The first line contains two integers n(2 <= n <= 100) and t(1 <= t <= 100), where n is the total number of positions on the running path, and t is the recording time interval of the GPS (in seconds).
The next n lines contain three integers per line. The i-th line has three integers Xi, yi (-10^6 <= xi, yi <=10^6), and ti (0 <= ti <= 10^6), giving the coordinates of the i-th position on the running path and the time (in seconds) that position is reached. The values of ti’s are strictly increasing. The first and last positions are the start and end of the run. Thus, t1 is always zero.
Given a sequence of positions and times for a running path, as well as the GPS recording time interval , calculate the percentage of the total run distance that is lost by the GPS. Your computations should assume that the runner goes at a constant speed in a straight line between consecutive positions.
My code can calculate the correct output out of the data from the picture but some of the test's will fail. The thing is that I dont now how the tests looks like. So I only know how the indata for the first test looks like.
int main(int arg, char* argv[]) {
int n, t;
int time, new_time, pos_x, pos_y, new_pos_x, new_pos_y;
double run_distance = 0, gps_distance = 0;
int gps_pos_x = 0, gps_pos_y = 0, gps_new_pos_x, gps_new_pos_y;
int gps_time = 0;
if(scanf("%d %d", &n, &t) != 2){
return 0;
}
if(scanf("%d %d %d", &pos_x, &pos_y, &time) != 3){
return 0;
}
for (int i = 0; i < n - 1; i++)
{
if(scanf("%d %d %d", &new_pos_x, &new_pos_y, &new_time) != 3){
return 0;
}
//Calculate run distance
run_distance += sqrt((new_pos_x - pos_x)*(new_pos_x - pos_x) + (new_pos_y - pos_y)*(new_pos_y - pos_y));
//Gps time
gps_time += t;
// Difference between new position X and old position X
int diff = new_pos_x - pos_x;
int pos;
// Difference between gps time and time of old position
int time_diff = gps_time - time;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_x;
// Save new position
gps_new_pos_x = pos;
// Difference between new position Y and old position Y
diff = new_pos_y - pos_y;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_y;
// Save new gps position
gps_new_pos_y = pos;
//printf("%d, %d\n", gps_new_pos_x, gps_new_pos_y);
//Calculate gps distance
gps_distance += sqrt((gps_new_pos_x - gps_pos_x)*(gps_new_pos_x - gps_pos_x) + (gps_new_pos_y - gps_pos_y)*(gps_new_pos_y - gps_pos_y));
pos_x = new_pos_x;
pos_y = new_pos_y;
time = new_time;
gps_pos_x = gps_new_pos_x;
gps_pos_y = gps_new_pos_y;
}
gps_distance += sqrt((pos_x - gps_pos_x)*(pos_x - gps_pos_x) + (pos_y - gps_pos_y)*(pos_y - gps_pos_y));
//float diffirence = run_distance - gps_distance;
float value = (run_distance - gps_distance)/run_distance * 100;
printf("%.15f\n", value);
return 0;
}

Related

Implementing equations with very small numbers in C - Plank's Law generating blackbody

I have a problem that, after much head scratching, I think is to do with very small numbers in a long-double.
I am trying to implement Planck's law equation to generate a normalised blackbody curve at 1nm intervals between a given wavelength range and for a given temperature. Ultimately this will be a function accepting inputs, for now it is main() with the variables fixed and outputting by printf().
I see examples in matlab and python, and they are implementing the same equation as me in a similar loop with no trouble at all.
This is the equation:
My code generates an incorrect blackbody curve:
I have tested key parts of the code independently. After trying to test the equation by breaking it into blocks in excel I noticed that it does result in very small numbers and I wonder if my implementation of large numbers could be causing the issue? Does anyone have any insight into using C to implement equations? This a new area to me and I have found the maths much harder to implement and debug than normal code.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//global variables
const double H = 6.626070040e-34; //Planck's constant (Joule-seconds)
const double C = 299800000; //Speed of light in vacume (meters per second)
const double K = 1.3806488e-23; //Boltzmann's constant (Joules per Kelvin)
const double nm_to_m = 1e-6; //conversion between nm and m
const int interval = 1; //wavelength interval to caculate at (nm)
//typedef structure to hold results
typedef struct {
int *wavelength;
long double *radiance;
long double *normalised;
} results;
int main() {
int min = 100 , max = 3000; //wavelength bounds to caculate between, later to be swaped to function inputs
double temprature = 200; //temprature in kelvin, later to be swaped to function input
double new_valu, old_valu = 0;
static results SPD_data, *SPD; //setup a static results structure and a pointer to point to it
SPD = &SPD_data;
SPD->wavelength = malloc(sizeof(int) * (max - min)); //allocate memory based on wavelength bounds
SPD->radiance = malloc(sizeof(long double) * (max - min));
SPD->normalised = malloc(sizeof(long double) * (max - min));
for (int i = 0; i <= (max - min); i++) {
//Fill wavelength vector
SPD->wavelength[i] = min + (interval * i);
//Computes radiance for every wavelength of blackbody of given temprature
SPD->radiance[i] = ((2 * H * pow(C, 2)) / (pow((SPD->wavelength[i] / nm_to_m), 5))) * (1 / (exp((H * C) / ((SPD->wavelength[i] / nm_to_m) * K * temprature))-1));
//Copy SPD->radiance to SPD->normalised
SPD->normalised[i] = SPD->radiance[i];
//Find largest value
if (i <= 0) {
old_valu = SPD->normalised[0];
} else if (i > 0){
new_valu = SPD->normalised[i];
if (new_valu > old_valu) {
old_valu = new_valu;
}
}
}
//for debug perposes
printf("wavelength(nm) radiance(Watts per steradian per meter squared) normalised radiance\n");
for (int i = 0; i <= (max - min); i++) {
//Normalise SPD
SPD->normalised[i] = SPD->normalised[i] / old_valu;
//for debug perposes
printf("%d %Le %Lf\n", SPD->wavelength[i], SPD->radiance[i], SPD->normalised[i]);
}
return 0; //later to be swaped to 'return SPD';
}
/*********************UPDATE Friday 24th Mar 2017 23:42*************************/
Thank you for the suggestions so far, lots of useful pointers especially understanding the way numbers are stored in C (IEEE 754) but I don't think that is the issue here as it only applies to significant digits. I implemented most of the suggestions but still no progress on the problem. I suspect Alexander in the comments is probably right, changing the units and order of operations is likely what I need to do to make the equation work like the matlab or python examples, but my knowledge of maths is not good enough to do this. I broke the equation down into chunks to take a closer look at what it was doing.
//global variables
const double H = 6.6260700e-34; //Planck's constant (Joule-seconds) 6.626070040e-34
const double C = 299792458; //Speed of light in vacume (meters per second)
const double K = 1.3806488e-23; //Boltzmann's constant (Joules per Kelvin) 1.3806488e-23
const double nm_to_m = 1e-9; //conversion between nm and m
const int interval = 1; //wavelength interval to caculate at (nm)
const int min = 100, max = 3000; //max and min wavelengths to caculate between (nm)
const double temprature = 200; //temprature (K)
//typedef structure to hold results
typedef struct {
int *wavelength;
long double *radiance;
long double *normalised;
} results;
//main program
int main()
{
//setup a static results structure and a pointer to point to it
static results SPD_data, *SPD;
SPD = &SPD_data;
//allocate memory based on wavelength bounds
SPD->wavelength = malloc(sizeof(int) * (max - min));
SPD->radiance = malloc(sizeof(long double) * (max - min));
SPD->normalised = malloc(sizeof(long double) * (max - min));
//break equasion into visible parts for debuging
long double aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm, nn, oo;
for (int i = 0; i < (max - min); i++) {
//Computes radiance at every wavelength interval for blackbody of given temprature
SPD->wavelength[i] = min + (interval * i);
aa = 2 * H;
bb = pow(C, 2);
cc = aa * bb;
dd = pow((SPD->wavelength[i] / nm_to_m), 5);
ee = cc / dd;
ff = 1;
gg = H * C;
hh = SPD->wavelength[i] / nm_to_m;
ii = K * temprature;
jj = hh * ii;
kk = gg / jj;
ll = exp(kk);
mm = ll - 1;
nn = ff / mm;
oo = ee * nn;
SPD->radiance[i] = oo;
}
//for debug perposes
printf("wavelength(nm) | radiance(Watts per steradian per meter squared)\n");
for (int i = 0; i < (max - min); i++) {
printf("%d %Le\n", SPD->wavelength[i], SPD->radiance[i]);
}
return 0;
}
Equation variable values during runtime in xcode:
I notice a couple of things that are wrong and/or suspicious about the current state of your program:
You have defined nm_to_m as 10-9,, yet you divide by it. If your wavelength is measured in nanometers, you should multiply it by 10-9 to get it in meters. To wit, if hh is supposed to be your wavelength in meters, it is on the order of several light-hours.
The same is obviously true for dd as well.
mm, being the exponential expression minus 1, is zero, which gives you infinity in the results deriving from it. This is apparently because you don't have enough digits in a double to represent the significant part of the exponential. Instead of using exp(...) - 1 here, try using the expm1() function instead, which implements a well-defined algorithm for calculating exponentials minus 1 without cancellation errors.
Since interval is 1, it doesn't currently matter, but you can probably see that your results wouldn't match the meaning of the code if you set interval to something else.
Unless you plan to change something about this in the future, there shouldn't be a need for this program to "save" the values of all calculations. You could just print them out as you run them.
On the other hand, you don't seem to be in any danger of underflow or overflow. The largest and smallest numbers you use don't seem to be a far way from 10±60, which is well within what ordinary doubles can deal with, let alone long doubles. The being said, it might not hurt to use more normalized units, but at the magnitudes you currently display, I wouldn't worry about it.
Thanks for all the pointers in the comments. For anyone else running into a similar problem with implementing equations in C, I had a few silly errors in the code:
writing a 6 not a 9
dividing when I should be multiplying
an off by one error with the size of my array vs the iterations of for() loop
200 when I meant 2000 in the temperature variable
As a result of the last one particularly I was not getting the results I expected (my wavelength range was not right for plotting the temperature I was calculating) and this was leading me to the assumption that something was wrong in the implementation of the equation, specifically I was thinking about big/small numbers in C because I did not understand them. This was not the case.
In summary, I should have made sure I knew exactly what my equation should be outputting for given test conditions before implementing it in code. I will work on getting more comfortable with maths, particularly algebra and dimensional analysis.
Below is the working code, implemented as a function, feel free to use it for anything but obviously no warranty of any kind etc.
blackbody.c
//
// Computes radiance for every wavelength of blackbody of given temprature
//
// INPUTS: int min wavelength to begin calculation from (nm), int max wavelength to end calculation at (nm), int temperature (kelvin)
// OUTPUTS: pointer to structure containing:
// - spectral radiance (Watts per steradian per meter squared per wavelength at 1nm intervals)
// - normalised radiance
//
//include & define
#include "blackbody.h"
//global variables
const double H = 6.626070040e-34; //Planck's constant (Joule-seconds) 6.626070040e-34
const double C = 299792458; //Speed of light in vacuum (meters per second)
const double K = 1.3806488e-23; //Boltzmann's constant (Joules per Kelvin) 1.3806488e-23
const double nm_to_m = 1e-9; //conversion between nm and m
const int interval = 1; //wavelength interval to calculate at (nm), to change this line 45 also need to be changed
bbresults* blackbody(int min, int max, double temperature) {
double new_valu, old_valu = 0; //variables for normalising result
bbresults *SPD;
SPD = malloc(sizeof(bbresults));
//allocate memory based on wavelength bounds
SPD->wavelength = malloc(sizeof(int) * (max - min));
SPD->radiance = malloc(sizeof(long double) * (max - min));
SPD->normalised = malloc(sizeof(long double) * (max - min));
for (int i = 0; i < (max - min); i++) {
//Computes radiance for every wavelength of blackbody of given temperature
SPD->wavelength[i] = min + (interval * i);
SPD->radiance[i] = ((2 * H * pow(C, 2)) / (pow((SPD->wavelength[i] * nm_to_m), 5))) * (1 / (expm1((H * C) / ((SPD->wavelength[i] * nm_to_m) * K * temperature))));
//Copy SPD->radiance to SPD->normalised
SPD->normalised[i] = SPD->radiance[i];
//Find largest value
if (i <= 0) {
old_valu = SPD->normalised[0];
} else if (i > 0){
new_valu = SPD->normalised[i];
if (new_valu > old_valu) {
old_valu = new_valu;
}
}
}
for (int i = 0; i < (max - min); i++) {
//Normalise SPD
SPD->normalised[i] = SPD->normalised[i] / old_valu;
}
return SPD;
}
blackbody.h
#ifndef blackbody_h
#define blackbody_h
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//typedef structure to hold results
typedef struct {
int *wavelength;
long double *radiance;
long double *normalised;
} bbresults;
//function declarations
bbresults* blackbody(int, int, double);
#endif /* blackbody_h */
main.c
#include <stdio.h>
#include "blackbody.h"
int main() {
bbresults *TEST;
int min = 100, max = 3000, temp = 5000;
TEST = blackbody(min, max, temp);
printf("wavelength | normalised radiance | radiance |\n");
printf(" (nm) | - | (W per meter squr per steradian) |\n");
for (int i = 0; i < (max - min); i++) {
printf("%4d %Lf %Le\n", TEST->wavelength[i], TEST->normalised[i], TEST->radiance[i]);
}
free(TEST);
free(TEST->wavelength);
free(TEST->radiance);
free(TEST->normalised);
return 0;
}
Plot of output:

Displaying a list of errors,when consecutive data is too far from the average,

I want to do 2 things:
display all voltages that differ from the average by more than 10% of the average and display all pairs of consecutive hours where the change from the voltage at one hour to the next is greater than 15% of the average.I have come into trouble with the second part.
#include <stdio.h>
#include <math.h>
int i, problem = 0, index;
float voltage[6];
float average, average10, average15, dif, total;
int main(){
total = 0.0;
for( index = 0; index < 6; index++ ){
printf( "Enter a voltage for hour %d: ", index+1 );
scanf( "%f", &voltage[index] );
total += voltage[index];
}
average = total / 6.0;
average10 = average / 10;
average15 = average / 100 * 15;
printf("The average is %1.1f\n", average);
printf("10%% = %1.1f\n", average10);
printf("15%% = %1.1f\n", average15);
for(index = 0; index < 6; index++){
dif = fabs(voltage[index] - average);
if(dif > (average10)){
problem++;
if(problem == 1){
printf("The following problems occurred:\n");}
printf("%d. Voltage at hour %d was %1.1f (difference of %1.1f volts)\n", problem, (i ++)+1, voltage[index], dif);
}
}
for(index = 1; index < 6; index++){
dif = fabs((voltage[i] - voltage[i-1] > average15));
if(dif > average15){
problem++;
if(problem == 1){
printf("The following problems occurred:\n");}
printf("%d Voltage change from hour %d to %d was %1.1f", problem, i, (i ++)+1 , dif);
}
}
if(problem = 0) printf("No problems were encountered.");
}
This displays the first part fine apart from the problem hours dont always display the right values (as seen here for problem number 2 not enough rep to embed sorry) http://gyazo.com/34fa038b11bf85effa195232f952cd76
but absolutely nothing appears for the second part or the printf if no problems occur . Do you guys have any ideas on how to make the values on the problems correctly line up and on why im not getting anything back from the second for loop
It is just a typo here:
dif = fabs((voltage[i] - voltage[i-1] > average15));
/* This means dif = fabs((0));
* dif = fabs((1));
* as the result of the > operator is 0 or 1
**/
Probably should be
dif = fabs(voltage[i] - voltage[i-1]);

find the length of any arc on a circle

I have an interesting (to me anyway) problem. I am working on OpenServo.org for V4 and I am trying to determine the length of an arc of travel and its direction.
I have a magnetic encoder that returns the position of the shaft from 0 to 4095.
The servo has two logical end points, call them MAX and MIN which are set in software and can be changed at any time, and the shaft must rotate (i.e. travel) on one arc between the MAX and MIN positions. For example in the picture the blue arc is valid but the red is not for all travel between and including MIN and MAX.
I am trying to work out a simple algorithm using only integer math that can tell me the distance between any two points A and B that can be anywhere on the circumference, bounded by MIN and MAX and with either A as the current place and B is the target position, or B is the current place and A is the target (which is denoted by a negative distance from B to A). Note the side I allowed to travel is known, it is either "red" or "blue".
The issue is when the 4095/0 exists in the ARC, then the calculations get a bit interesting.
You need to adjust all your coordinates so they're on the same side of your limit points. Since it's a circular system you can add 4096 without affecting the absolute position.
lowest = min(MIN, MAX);
if (A < lowest)
A += 4096;
if (B < lowest)
B += 4096;
distance = B - A; /* or abs(B - A) */
In your example A would not be adjusted but B would be adjusted to 5156. The difference would be a positive 1116.
In your second example with A=3000 and B=2500, they're both above 2000 so neither would need adjustment. The difference is -500.
Here's a simple algorithm:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int rotate_diff(int a, int b, bool * clockwise);
int main(void) {
int degrees_rotated, a, b;
bool clockwise;
a = 4040;
b = 1060;
degrees_rotated = rotate_diff(a, b, &clockwise);
printf("A = %d, B = %d, rotation = %d degrees, direction = %s\n",
a, b, degrees_rotated,
(clockwise ? "clockwise" : "counter-clockwise"));
return EXIT_SUCCESS;
}
int rotate_diff(int a, int b, bool * clockwise) {
static const int min = 2000;
if ( a <= min ) {
a += 4096;
}
if ( b <= min ) {
b += 4096;
}
int degrees_rotated = b - a;
if ( degrees_rotated > 0 ) {
*clockwise = false;
} else {
degrees_rotated = -degrees_rotated;
*clockwise = true;
}
return degrees_rotated * 360 / 4096;
}
Note that this gives you the degrees traveled, but not the distance traveled, since you don't tell us what dimensions of the shaft are. To get the distance traveled, obviously multiply the circumference by the degrees traveled divided by 360. If your points 0 through 4095 are some kind of known units, then just skip the conversion to degrees in the above algorithm, and change the variable names accordingly.
Unless I missed something, this should give the result you need:
if MIN < A,B < MAX
distance = A - B
else
if A > MAX and B < MIN
distance = A - (B + 4096)
else if B > MAX and A < MIN
distance = (A + 4096) - B
else
distance = A - B
(get the absolute value of the distance if you don't need the direction)

Improvement to my Mandelbrot set code

I have the following Mandelbrot set code in C. I am doing the calculation and creating a .ppm file for the final fractal image. The point is that my fractal image is upside down, meaning it is rotated by 90 degrees. You can check it by executing my code:
./mandel > test.ppm
On the other hand, I also want to change the colours. I want to achieve this fractal image:
My final issue is that my code doesn't check the running time of my code. I have the code for this part too, but when code execution finishes it doesn't print the running time. If someone can make the appropriate changes to my code and help me achieve this fractal image, and make elapsed time displayed I would be glad.
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
void color(int red, int green, int blue)
{
fputc((char)red, stdout);
fputc((char)green, stdout);
fputc((char)blue, stdout);
}
int main(int argc, char *argv[])
{
int w = 600, h = 400, x, y;
//each iteration, it calculates: newz = oldz*oldz + p, where p is the current pixel, and oldz stars at the origin
double pr, pi; //real and imaginary part of the pixel p
double newRe, newIm, oldRe, oldIm; //real and imaginary parts of new and old z
double zoom = 1, moveX = -0.5, moveY = 0; //you can change these to zoom and change position
int maxIterations = 1000;//after how much iterations the function should stop
clock_t begin, end;
double time_spent;
printf("P6\n# CREATOR: E.T / mandel program\n");
printf("%d %d\n255\n",w,h);
begin = clock();
//loop through every pixel
for(x = 0; x < w; x++)
for(y = 0; y < h; y++)
{
//calculate the initial real and imaginary part of z, based on the pixel location and zoom and position values
pr = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX;
pi = (y - h / 2) / (0.5 * zoom * h) + moveY;
newRe = newIm = oldRe = oldIm = 0; //these should start at 0,0
//"i" will represent the number of iterations
int i;
//start the iteration process
for(i = 0; i < maxIterations; i++)
{
//remember value of previous iteration
oldRe = newRe;
oldIm = newIm;
//the actual iteration, the real and imaginary part are calculated
newRe = oldRe * oldRe - oldIm * oldIm + pr;
newIm = 2 * oldRe * oldIm + pi;
//if the point is outside the circle with radius 2: stop
if((newRe * newRe + newIm * newIm) > 4) break;
}
color(i % 256, 255, 255 * (i < maxIterations));
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Elapsed time: %.2lf seconds.\n", time_spent);
return 0;
}
Part 1:
You need to swap the order of your loops to:
for(y = 0; y < h; y++)
for(x = 0; x < w; x++)
That will give you the correctly oriented fractal.
Part 2:
To get the time to print out, you should print it to stderr since you are printing the ppm output to stdout:
fprintf(stderr, "Elapsed time: %.2lf seconds.\n", time_spent);
Part 3:
To get a continuous smooth coloring, you need to use the Normalized Iteration Count method or something similar. Here is a replacement for your coloring section that gives you something similar to what you desire:
if(i == maxIterations)
color(0, 0, 0); // black
else
{
double z = sqrt(newRe * newRe + newIm * newIm);
int brightness = 256. * log2(1.75 + i - log2(log2(z))) / log2(double(maxIterations));
color(brightness, brightness, 255);
}
It isn't quite there because I kind of did a simple approximate implementation of the Normalized Iteration Count method.
It isn't a fully continuous coloring, but it is kind of close.

Declared variable not showing up in Locals of Debugger

This is a simple program to calculate the length of lines. All the calculation aspects of the program are done and working.
But I am having trouble on one very simple aspect, the variable "percent_detoured" is declared on line 10 and used on line 83, and printed on line 84. Problem is when executed, everything else runs fine but percent_detoured consistently returns 0.000. When debugged, percent_detoured does not even show as a variable in "Locals".
I am using Pelles C IDE if that helps.
Thanks for the help!
{
float line_value;
int x_1, y_1, x_2, y_2;
float y_intercept;
float distance, greatest_distance, total;
float percent_detoured; // <-- DECLARED HERE (SCROLL ALL THE WAY DOWN TO SEE WHERE IT IS USED)
int count, detour_count;
x_1=1; y_1=1; x_2=1; y_2=1;
greatest_distance = 0; total = 0; count = 0; detour_count = 0;
/* Ask for user input in setting the coordinates of the line */
printf("Enter in the length of the line\n");
scanf("%f", &line_value);
/* If user enters in y coordinates for the line such that the line length is greater
than 10 units, then enter loop and continue looping until the length is smaller or
equal to 10 */
while ( line_value > 10 || line_value < 0)
{
printf("Try Again. Value should be smaller or equal to 10 units\n");
scanf("%f", &line_value);
}
line_value = line_value / 2; //Define the top of the line
printf("Enter x and y coordinates for point 1 and 2\n");
scanf("%d %d %d %d", &x_1, &y_1, &x_2, &y_2);
if ( x_1 == 0 && x_2 == 0 && y_1 == 0 && y_2 == 0 ) //If user enters in 0 0 0 0 right away, then immediately end the program
{
printf("No path lengths have been calculated\n");
}
else
{
/* While the user does not enter in the values 0 0 0 0 for all coordinates, continue while loop */
while ( (x_1 != 0) || (y_1 != 0) || (x_2 != 0) || (y_2 != 0) )
{
y_intercept = y_1 - ( (y_2 - y_1) / (x_2 - x_1) * x_1 ); //Rearrange (y=mx+b) to get (b=y-mx) where b is the y intercept
if ( y_intercept <= line_value && y_intercept >= 0 ) //If the y-intercept of the line from point a to b is between
{ //the top of L and 0, then calculate distance between a and top of L
distance = sqrt( pow(x_1, 2) + pow((y_1 - line_value), 2) )
+ sqrt( pow(x_2, 2) + pow((line_value - y_2), 2) );
detour_count++; //Updating the detour counter
}
else if ( y_intercept >= ( line_value * -1) && y_intercept < 0 ) //If the y-intercept of the line from point a to b is between
{ //the bottom of L and 0, then calculate distance between a and bottom of L
distance = sqrt( pow(x_1, 2) + pow( (y_1 + line_value), 2) )
+ sqrt( pow(x_2, 2) + pow(( y_2 - (line_value * -1) ), 2) );
detour_count++; //Updating the detour counter
}
else
{
distance = sqrt( pow((x_2 - x_1), 2) + pow((y_2 - y_1), 2)); //If shortest path between point a and b does not cross L,
} //then the distance is just the sum of squares of rise and run
if (distance > greatest_distance)
{
greatest_distance = distance; //If the current distance is greater than the previous, set it as the greatest distance
}
total = total + distance; //Total count of distance
count++; //Update general counter
printf("The shortest path is: %f\n", distance);
printf("Enter x and y coordinates for point 1 and 2\n");
scanf("%d %d %d %d", &x_1, &y_1, &x_2, &y_2);
}
}
printf("\nThe average path length: %f\n", (total/count));
printf("The length of the longest path: %f\n", greatest_distance);
percent_detoured = ((detour_count/count) * 100); // <-- USED IT HERE
printf("The percentage of paths involving a detour: %f\n", percent_detoured ); // <-- SHOULD BE PRINTED AS ITS VALUE HERE
return 0;
}
You should use
percent_detoured = ((float)detour_count/count) * 100.0);
Else, both detour_count and count are integers, and int divided by int will give an int. So assuming that detour_count < count, detour_count/count will be rounded to 0, multiplied by 100 (still 0) and finally rounded to float since it is being stored as a float (percent_detoured).
I never used the IDE you mentioned, so I have no clue why it might not be showing up in the debugger. :)

Resources