对整数值的数字进行分类

时间:2015-02-21 04:56:01

标签: c++

我在这段代码上花了一天时间来计算偶数和零和奇数

从long数据类型我使用函数发送数据。这是代码

#include <iostream>
using namespace std;

void digitCount(long long int &num);

int main ()
{
    long long int num;

    cout <<"Enter any No. " <<endl;
    cin >>num;
    cout <<endl;

    digitCount(num);

    return 0;
}


void digitCount(long long  int &num)
{
    int e = 0, z = 0, o = 0, x = 0;
    for (int i = 0; i <= num; i++)
    {
        x= num % 10;    
        if(x == 0)
        {
            ++z;
            num = num / 10;
        }
        else if(x%2==1)
        {
            ++o;
            num = num / 10;
        }
        else
        {
            ++e;
            num = num / 10;
        }  
    }

    cout << "No of zeros Digits = " << z<< endl;
    cout << "No of odd Digits = " << o << endl;
    cout << "No of Even Digits = " << e << endl;
}
问题是,当我计算奇数时,有一个错过的数字

例如我输入时:12345

结果是

no of even : 2 
no of odd :  2 (should be 3)
no of zero : 0 

这里的问题是:

编写一个函数,该函数将参数作为整数(作为长整数值)并返回奇数,偶数和零数字的数字。还要编写一个程序来测试你的功能。使用传递参考方法。

1 个答案:

答案 0 :(得分:3)

而不是for循环,你应该使用:

while (num > 0)

您不断更改num,当它变为1时(在您的12345示例中),i为3.我还修改了您的digitcount以展示一些不错的格式可读代码。

void digitCount(long long  int &num) {  
    int e(0), z(0), o(0), x(0);

    while (num > 0) {
        x = num % 10;

        if (x == 0) {
            z++;
        }
        else if (x % 2 == 1) {
            o++;
        }
        else {
            e++;
        }

        num /= 10;
    }

    cout << "No of zeros Digits = " << z << endl;
    cout << "No of odd Digits = " << o << endl;
    cout << "No of Even Digits = " << e << endl;
}

如果您认为这可以解决您的问题&amp;&amp;是最好的答案,请点击此答案旁边的复选标记。感谢

相关问题