简体   繁体   English

我如何 output 数组的元素(在奇数位置,有奇数的偶数位数?

[英]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.如果我有 4 个元素,按以下顺序:4 10 2546 和 100、4 和 2546 在奇数位置,4 有 1 个偶数位,2546 有 3 个偶数位,所以 output 应该是“4 2546”,但是我的程序只有输出“0 0”,我认为这是因为while循环,但我不知道如何修复它。

#include <iostream>

using namespace std;

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

    cout << "How many elements?\n";
    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;
}

You made a small typo.你犯了一个小错字。

In the cout statement you your showing the value of x, which has been made 0 by the divisions.在 cout 语句中,您显示 x 的值,该值已被除法设为 0。

You need to show the original valeu, stored in v[i].您需要显示存储在 v[i] 中的原始值。

So, please modify you cout statement to:因此,请将您的 cout 语句修改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM