# Thread: problem about handle "double" variable type? or?

1. ## problem about handle "double" variable type? or?

I am doing a problem about calcuating first digit of a^p form(a and p are non-negative integer. The total length of a^p never exceed 200). a and p may be a very large number. So I wanna make variable a to double type. and then a always range between 0 < a < 10. Like a = 1234 --> 1.234. But the answer is wrong explained by http://acm.hnu.cn:8080/online/?actio...=show&id=10695. Notice: The input and output field can be seperated itself.
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_S 300

double str2double(char *s)
{
double a;
int i;
s[strlen(s)] = '\0';
if (strlen(s) > 1) {
s[strlen(s)+1] = '\0';
for (i = strlen(s); i >= 2; i--)
s[i] = s[i-1];
s[1] = '.';
}
a = atof(s);
return a;
}

int firstDigit(double a, int p)
{
int i;
double x = a;
for (i = 1; i < p; i++) {
x *= a;
if (x >= 10) x /= 10;
}
return (int)x;
}

int main()
{
char s[MAX_S];
int n, p, x, i;
double a;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%s %d", s, &p);
printf("%s\n", s);
a = str2double(s);
x = firstDigit(a, p);
printf("%d\n", x);
}
return 0;
}```
I don't know what is the error here. if everyone know, please reply. Thanks.

2. > The total length of a^p never exceed 200). a and p may be a very large number. So I wanna make variable a to double type.
But doubles are only good for about 15 digits of precision, so any answer you calculate using doubles is going to be approximate.
However, since you're only interested in the most significant digit, maybe that's enough.

If you really need all that precision, you need a math library like this.
http://www.swox.com/gmp/

Consider that there may be a 'mathematical' answer to this problem, in the same way that spigots can calculate digits of say PI.

3. But I cannot call extending library. Because the online judge doesn't accept that. And my friend told me that I had solved this problem using the method I have mentioned above by pascal language. And I saw that many people solved it with short code compiled by GCC. The length code range 1xxB to 9xxB.

4. maybe printf("%s\n", s); should not be there?

also s[strlen(s)] = '\0'; has no meaning, if strlen return some value, it means it already found at this location the 0 character

5. It is is fully solvable without using any extra library.
All the code you have so far is of no value towards solving the problem. You cannot use doubles for this task.
The problem is that your approach is completely wrong. You need to go back to basics and rethink how to represent things. None of the built-in datatypes are sufficient to individually represent the numbers required here. Back to the drawing board for you!

Popular pages Recent additions