0

So I have an assignment of adding up all of the digits of a number for example of 3256 would be 3+2+5+6 And so what I did was change the number into a string first and add all of the numbers of the string. However, the problem is that the string only takes them as chars and prints everything for example my number is 2^352 = 9.1779 e+105

So my array[1] = .

THis is what i have so far:

int calcular2()
{
    double r;
    r = pow(2, 352);
    n = 0;
    printf("2^352 es: %0.0f\n", r);

    std::ostringstream ostr;
    ostr << r;
    std::string resultado = ostr.str();

    for (int j = 0; j < 127; j++)
    {
        if (resultado[1] == '.')
            continue;
        n = resultado[j] + n;
    }

    printf("La suma de todos los digitos de 2^352 es:");
    printf("%d\n", n);

    return 0;
}

So what I dont understand is how to add up all the numbers in resultado[j] and so that it doesnt consider r as 9.17799e+105 since resultado[8] prints as e and so far.

user207421
  • 305,947
  • 44
  • 307
  • 483
Seung
  • 29
  • 1
  • 2
  • 6
  • Have a look at the question and answers [asc and chr equivalent in C/C++](http://stackoverflow.com/questions/6405137/asc-and-chr-equivalent-in-c-c) and you may see a way to resolve your difficulty. – Simon Jan 20 '15 at 02:58
  • 3
    Do you know that a `double` only has a precision of 15-16 decimal digits? – user253751 Jan 20 '15 at 03:02
  • @immibis Yes and that's a problem, however in linux for some weird reason, it actually does print all of the digits even after 15-16 decimal digits but the problem is what Simon linked me to. It adds the literal raw numerical values of each of the numbers in the string rather than the normal values im looking for. – Seung Jan 20 '15 at 03:07
  • 2
    @Seung you are mistaken. I understand that you can print more than 16 digits of a `double` but only the first 16 digits at most are **correct**. The remaining digits are just a rounding artifact from displaying the value in base 10. As the result of a math operation, they are no more correct than any other digits, chosen at random. – Drew Dormann Jan 20 '15 at 03:18
  • @DrewDormann Oh... okay, I guess that makes sense why in visual studio it appears as zeros. May i ask something different though? Would you happen to know how to change the raw numerical values of each character in the string into normal numbers? I was thinking of making it as an array but I have no idea to be honest – Seung Jan 20 '15 at 03:21
  • possible duplicate of [How to convert char to integer in C?](http://stackoverflow.com/questions/868496/how-to-convert-char-to-integer-in-c) – user253751 Jan 20 '15 at 03:50

0 Answers0