stuck at getting multiples of number

时间:2018-03-23 00:36:19

标签: c++

I'm try to Find the sum of all the multiples of nums below range, but i have some problem with loop

int sumOfNumberMuliplesOf(int range, vector<int> nums) {
    int sum;
    vector<int> num;

    // get the number and its multiples
    for (int x : nums) {
        if (x != 0) {
        for (int i = x; x < range; i+= x) {
            num.push_back(x);
            cout<< x << "  "; // stuck on 3  .... PROBLEM IN THIS LOOP
        }
    }
}

/// check for duplicated numbers
        for (int x = 0;x < num.size();x++) {
            for (int  y = x+1; y < num.size(); y++) {
                if (num[x] == num[y]) {
                num[y] = 0;
                }
            }
        }
// sum the numbers
        for (int x = 0; x< num.size(); x++) {
            sum+=num[x];
        }
        return sum;
}
int main() {
    vector<int> num;
    num.push_back(3);
    num.push_back(5);
    cout << sumOfNumberMuliplesOf(1000,num);
    return 0;
    }

why integer 'i' stuck on '3' and not increased by x?

1 个答案:

答案 0 :(得分:1)

for (int i = x; x < range; i+= x) {
    num.push_back(x);
    cout<< x << "  "; // stuck on 3  .... PROBLEM IN THIS LOOP
}

There very much is a problem in that loop, since the only variable you're changing is i and yet the variable you're checking, adding to the vector, and printing, is the unchanging x.