0

I'm new here and actually

I've got a problem in my mind, and it's like this:

I get an input of a vector of any size, but for this case, let's take this one:

vetor = {1, 2, 3, 4}

Now, all I want to do is to take this numbers and sum each one (considering it's unity, tens, hundred, thousand) and register the result into a integer variable, for the case, 'int vec_value'.

Considering the vector stated above, the answer should be: vec_value = 4321.

I will leave the main.cpp attached to the post, however I will tell you how I calculated the result, but it gave me the wrong answer.

vetor[0] = 1

vetor[1] = 2

vetor[2] = 3

vetor[3] = 4

the result should be = (1*10^0)+(2*10^1)+(3*10^2)+(4*10^3) = 1 + 20 + 300 + 4000 = 4321.

The program is giving me the solution as 4320, and if I change the values randomly, the answer follows the new values, but with wrong numbers still.

If anyone could take a look at my code to see what I'm doing wrong I'd appreciate it a lot!

Thanks..

There's a link to a picture at the end of the post showing an example of wrong result. Keep in mind that sometimes the program gives me the right answer (what leaves me more confused)

Code:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <cmath>

using namespace std;

int main()
{
    vector<int> vetor;

    srand(time(NULL));
    int lim = rand() % 2 + 3; //the minimum size must be 3 and the maximum must be 4
    int value;

    for(int i=0; i<lim; i++)
    {
        value = rand() % 8 + 1; // I'm giving random values to each position of the vector
        vetor.push_back(value);
        cout << "\nPos [" << i << "]: " << vetor[i]; //just to keep in mind what are the elements inside the vector
    }

    int vec_value=0;

    for(int i=0; i<lim; i++)
    {
        vec_value += vetor[i] * pow(10, i); //here i wrote the formula to sum each element of the vector with the correspondent unity, tens, hundreds or thousands
    }

    cout << "\n\nValor final: " << vec_value; //to see what result the program will give me

    return 0;
}

Example of the program

3
  • 1
    Works for me, exactly as written. Oct 2, 2018 at 3:32
  • @IgorTandetnik thanks for answering. The code works properly every time you run it? It just works for me AND my friend like, 3 times in 10. We really don't know whats we're supposed to do with that
    – casarin
    Oct 2, 2018 at 7:06
  • could be due inaccurate std::pow results: stackoverflow.com/questions/15851636/…
    – kmdreko
    Oct 2, 2018 at 7:20

1 Answer 1

0

Try this for the main loop:

int power = 1;
for(int i=0; i<lim; i++)
{
    vec_value += vetor[i] * power;
    power *= 10;
}

This way, all the computations are in integers, you are not affected by floating point rounding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.