Home > OS >  How do I multiply vector integers
How do I multiply vector integers

Time:09-28

so basically I want to multiply a vector by 60 from seconds to minutes and hours 3 times using a for loop. I also want to add 3 more values inside that vector that should store a value 60 times greater than the last integer before it.

This is what I have come up so far but it only prints out 2 times so what am I doing wrong?

#include <iostream>
#include <vector>

int main() {
    std::vector <int> seconds = { 1 };

    for (int i = 0; i <= 3; i  ) {
        i = seconds.at(i) * 60;
        seconds.push_back(i);
    }
    
    for (int i = 0; i < seconds.size(); i  ) {
        std::cout << seconds[i] << std::endl;
    }

    return 0;
}

CodePudding user response:

This for loop iterates exactly once.

std::vector <int> seconds = { 1 };

for (int i = 0; i <= 3; i  ) {
    i = seconds.at(i) * 60;
    seconds.push_back(i);
}

i is set to 60, and the loop condition i <= 3 then fails.

Use a different variable to hold this value.

std::vector <int> seconds = { 1 };

for (int i = 0; i <= 3; i  ) {
    auto x = seconds.at(i) * 60;
    seconds.push_back(x);
}

Or don't use a variable at all.

std::vector <int> seconds = { 1 };

for (int i = 0; i <= 3; i  ) {
    seconds.push_back( seconds.at(i) * 60 );
}
  • Related