Question

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.

Was it helpful?

Solution 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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top