rbprogrammer

August 29th, 2007, 05:05 PM

maybe today just isnt the best programming day, or maybe i'm just tired or whatever.. but i cant seem to see why this code does not work

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

{

int length = 3;

float *numbers = (float*)malloc( length * sizeof(float) );

float total = 0.0f;

float average = 0.0f;

int i = 0;

for(i=0; i<length; i++)

{

printf("Please enter in a number for index %02i: ", (i+1));

scanf("%f", &numbers[i]);

total += numbers[ i ];

printf("number: %f\n", numbers[i]);

printf("total: %f\n", total);

printf("length: %d\n", length);

}

average = total / (float)length;

printf("The Average is: %.2f\n\n", &average);

free( numbers );

return 0;

}

and then i compile, but i get errors:

$ gcc file.c

$ ./a.out

Please enter in a number for index 01: 5

number: 5.000000

total: 5.000000

length: 3

Please enter in a number for index 02: 10

number: 10.000000

total: 15.000000

length: 3

Please enter in a number for index 03: 15

number: 15.000000

total: 30.000000

length: 3

The Average is: 30.00

but if i were to comment out those printf()'s that were just used for debugging, i get

$ ./a.out

Please enter in a number for index 01: 5

Please enter in a number for index 02: 10

Please enter in a number for index 03: 15

The Average is: -0.33

clearly this program is just supposed to average a few numbers, and in this case, the average was supposed to be 10.

what's going on?

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

{

int length = 3;

float *numbers = (float*)malloc( length * sizeof(float) );

float total = 0.0f;

float average = 0.0f;

int i = 0;

for(i=0; i<length; i++)

{

printf("Please enter in a number for index %02i: ", (i+1));

scanf("%f", &numbers[i]);

total += numbers[ i ];

printf("number: %f\n", numbers[i]);

printf("total: %f\n", total);

printf("length: %d\n", length);

}

average = total / (float)length;

printf("The Average is: %.2f\n\n", &average);

free( numbers );

return 0;

}

and then i compile, but i get errors:

$ gcc file.c

$ ./a.out

Please enter in a number for index 01: 5

number: 5.000000

total: 5.000000

length: 3

Please enter in a number for index 02: 10

number: 10.000000

total: 15.000000

length: 3

Please enter in a number for index 03: 15

number: 15.000000

total: 30.000000

length: 3

The Average is: 30.00

but if i were to comment out those printf()'s that were just used for debugging, i get

$ ./a.out

Please enter in a number for index 01: 5

Please enter in a number for index 02: 10

Please enter in a number for index 03: 15

The Average is: -0.33

clearly this program is just supposed to average a few numbers, and in this case, the average was supposed to be 10.

what's going on?