Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c++ - How do I output the array's elements (on odd positions, that have an odd amount of even digits?

If I have 4 elements, in this order: 4 10 2546 and 100, 4 and 2546 are on odd positions, 4 has 1 even digit and 2546 has 3 even digits, so the output should be "4 2546", however my program only outputs "0 0", and I think it's because of the while loop, but I don't know how to fix it.

#include <iostream>

using namespace std;

int main()
{
    int n, evenDigits = 0, r, x;

    cout << "How many elements?
";
    cin >> n;

    int* v = new int[n];

    for(int i=0; i<n; i++)
        cin >> v[i];

    for(int i=0; i<n; i=i+2){

        evenDigits = 0;
        x = v[i];

        while(x != 0){
            r = x % 10;
            if(r % 2 == 0)
                evenDigits++;
            x /= 10;
        }
        if(evenDigits % 2 == 1)
            cout << x << " ";

    }
    return 0;
}
question from:https://stackoverflow.com/questions/65861096/how-do-i-output-the-arrays-elements-on-odd-positions-that-have-an-odd-amount

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You made a small typo.

In the cout statement you your showing the value of x, which has been made 0 by the divisions.

You need to show the original valeu, stored in v[i].

So, please modify you cout statement to:

cout << v[i] << " ";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...