Hi,
I want to declare an array size based on a double calculation. Rounding it up or down doesn't really matter. As the array size needs to be an integer, is there any way I can convert the double result to an integer?
Printable View
Hi,
I want to declare an array size based on a double calculation. Rounding it up or down doesn't really matter. As the array size needs to be an integer, is there any way I can convert the double result to an integer?
i = (int)d;
Otherwise known as "look it up".
Rounding it up or down probably does matter. Depending on round-off error and all that good stuff. If the result was very close to an integer (meant to be an integer but could be +/- some tiny fraction) you have to find the closest integer. Usually something like
Code:i = (int)(d + 0.5);
I need to use the int value to declare the array size. However when I try the suggested responses it does not work.
It says "integral constant expression expected"
double z = x/y;
int a = (int) z;
int array1 = [a];
That is not how you declare an array. You need to pick up a book, or read through some tutorials online.Code:int array1 = [a];
At any rate, try this:Code:int array1[a];
That is because unless you are compiling with respect to C99, this is wrong:Quote:
Originally Posted by millsy5
You are trying to create a variable length array, and that is not allowed in standard C prior to the 1999 edition of the C standard.Code:int a = (int) z;
int array1[a];
check out malloc:
#include <stdlib.h>
int *array1 = NULL;
array1 = malloc(a * sizeof(int));
memory allocated by malloc should be later freed and the pointer set to null:
free(array1);
array1 = NULL;