lundi 1 octobre 2018

Get a number value from Vector positions

Well guys, I'm new here and actually I'm on the 2nd year at college but let's go to the question.

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

Aucun commentaire:

Enregistrer un commentaire