RTriplett - 1 year ago 51

C Question

I'm working on a program for my programming class in college. I got most of it to work properly,but the end loop i'm trying to use doesn't work right. I'm not quite sure whats going on. I like to learn more and figure out why it's doing this. My problem is at the end where I show the increase between years in a percentage. I'm trying to take the (year+1)-year/(year+1). Now I have my variables as integers and I want to cast my denominator to a float point. My answers kept coming up with 100.00%, -1.#J%, and 98.24% when I run the program. Below is a copy of what I got so far. An help will be gladly appreciated.

`#include <stdio.h>`

#include <stdlib.h>

#define years 4

#define months 12

int main(void)

{

float percentage [4];

float answer = 0.0;

int i = 0, j = 0, n = 0, sum = 0;

int time[] = {2012,2013,2014,2015};

int value[years];

const char* name[]= {" JAN "," FEB ", " MAR ", " APR ", " MAY ", " JUN ", " JUL ","AUG "," SEP "," OCT "," NOV "," DEC "};

int range[years][months] = {

{ 5626, 5629, 5626, 5606, 5622, 5633, 5647, 5656, 5673, 5682, 5728, 5728},

{ 5741, 5793, 5814, 5811, 5831, 5854, 5857, 5874, 5900, 5923, 5954, 5939},

{ 5999, 6020, 6062, 6103, 6115, 6128, 6169, 6194, 6219, 6233, 6256, 6301},

{ 6351, 6378, 6371, 6409, 6426, 6426, 6437, 6441, 6451, 6484, 6549, 6597}

};

printf("YEAR");

for(n=0; n < months; n++)

printf("%s", name[n]);

for (i = 0; i < years; i++) {

printf(" \n%i ", time[i]);

for (j = 0; j < months; j++)

printf("%2i ", range[i][j]);

printf("\n");

}

for (i = 0; i < years; i++) {

for(j = 0, sum = 0; j < months; j++)

sum += range[i][j];

printf("\n This is the sum of months for %i: %i", time[i], sum);

}

printf("\n\n");

for (i = 0; i < years-1; i++)

{

value[i] = 0;

for(j = 0, sum = 0; j < months; j++)

{

value[i] += range[i][j];

percentage[i]= (value[i+1]-value[i])/(float)value[i+1];

}

printf("\n The increase from %i to %i was: %.2f%% ", time[i], time[i+1], percentage[i]*100);

}

return 0;

}

Answer Source

In the last for loop, you can't say `percentage[i]= (value[i+1] -value[i])/(float)value[i+1];`

because you haven't initialized `value[i+1]`

yet. Only thing you can do is to use backward indexing like `((float)value[i] - (float)value[i-1])/(float)value[i];`

In the case of the first calculation, it won't work but in the first calculation, you have 0% increase because it is the first year and you have nothing to compare with.

Actually, try this. I think this will match your goal:

```
printf("\n\n");
for (i = 0; i < years; i++) {
value[i] = 0;
for(j = 0, sum = 0; j < months; j++) value[i] += range[i][j];
}
for(i = 0; i < years-1; i++) {
percentage[i]= (value[i+1]-value[i])/(float)value[i+1];
printf("\n The increase from %i to %i was: %.2f%% ", time[i], time[i+1], percentage[i]*100);
}
```