How to make a variable float complex or double complex depending on user input?
I’m trying to plot the Mandelbrot set and I have the same long code for float and double but in some cases float is not precise enough and double is too slow. I’d like to let the user choose precision over speed or speed over precision. I would like to get something like this:
int user_input;
scanf("%d", &user_input);
switch (user_input) {
case 0:
float z;
float c;
break;
case 1:
double z;
double c;
break;
}
for(int i=0;i<1920;i++){
for(int j=0;j<1080;j++){
z=0.0+0.0*I;
c=(i+j*I)/Zoom
}}
Expected outcome: if the user types 0, then all the calculations are performed using floats, and if the user types 1, the calculations are performed using doubles.
But this throws error: conflicting types for ‘z’; have ‘double’, previous declaration of ‘z’ with type ‘float’.
Is something like this possible in C?
I tried making two different varables for float and double but changing them in all the code (I have way more code) would be long and tedious.
Lol ilol is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can’t. The compiler needs to know the type of the variable in order to generate the appropriate code.
In your scenario, I would create a program that could be compiled into two different executables: one that uses float
, and one that uses double
.
#ifdef USEDOUBLE
typedef double Number;
#else
typedef float Number;
#endif
Number z;
gcc plot.c -o plot_float
gcc -DUSEDOUBLE plot.c -o plot_double
Another possibility is to create two versions of everything. You don’t want to actually write two of everything, so you’d use the earlier approach to create two libraries, then load the appropriate one at run-time.