How to store floats in array to be used later?
how can a user of a program store info in arrays such as a float number and can be calculated for an average late开发者_开发百科r in the program? im trying to make a program to calculate someones grade point average.
int maxGrades = 50; // pick this
int numGrades = 0;
float[] grades = malloc (sizeof (float) * maxGrades);
// in a loop somewhere
if(numGrades == maxGrades) {
maxGrades *= 2;
float[] newGrades = malloc (sizeof (float) * maxGrades);
for(int i = 0; i < numGrades; i++) newGrades[i] = grades[i];
grades = newGrades;
}
grades[numGrades++] = theNewestGrade;
Transitting from java to C, the biggest "concept jump" you have to make is Pointers.
Try allocating your floats this way:
float *float_array = malloc(amount_of_elemts_in_array * sizeof(float))
You can then iterate through using
float_array[index]
Having this pointer will enable you to pass float_array
in and out of functions by reference which is a great convenience since you don't want to recreate instances over every function call.
Pass float_array
into functions using:
Function Declaration: void function_that_uses_float_array(float *placeholder);
Function Call: function_that_uses_float_array(placeholder);
Pass float_array
out of functions using:
Return statement: return a_float_pointer;
One level up the stack: float_array = function_that_returns_a_float_pointer();
Arrays are automatically passed by reference.
Hope this helps point you in the right direction.
精彩评论