Pregunta

If I have

a = 3;
b = 5;

How can I make it so that

double result = 3e5, but only using variables?

I know aeb won't work, obviously.

¿Fue útil?

Solución 2

Use the function atof defined in stdlib.h and sprintf:

float a = 3;
int b = 5;

char tmp[10];
sprintf(tmp, "%fe%d", a, b);

double x = atof(tmp);
printf("x = %fe%d = %f\n", a, b, x);

Output: http://ideone.com/NdDcNB

x = 3.000000e5 = 300000.000000

Otros consejos

Try:

double result = a * pow(10.0,(double)b);

Or, with GNU extensions:

double result = a * exp10((double)b);

In either case, #include math.h and link with the math library (eg. -lm). This is likely much more efficient than piecing together a string and converting to double.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top