奇数,偶数,零计数器

时间:2015-11-04 00:05:13

标签: c++

我必须编写一个代码来计算多位长变量中奇数,偶数和零的数量,这是我到目前为止所做的:

#include <iostream>
using namespace std;

int lab14(long num, int &even, int &odd, int &zero){

    while (num > 0){

        long w = num;
        w = num%10;

        if (w % 2 == 1){
            odd++;
        }

        else if (w % 2 == 0 && w != 0){
            even++;
        }

        else if (w == 0 ){
            zero++;
        }

        num = num/10;

    }
    return odd;
    return even;
    return zero;
}

int main() {

    int even = 0, odd = 0, zero = 0;
    int num;

    cout << "#############################" << endl;

    cout << "## Even, odd, zero counter " << endl;

    bool flag = true;

    while (flag){

    cout << "## Please enter a #: "; cin >>num;


    lab14(num, even, odd, zero);

    cout << "## Even numbers: "<<  even << endl
         << "## Odd Numbers: " << odd << endl
         << "## Zeros: " << zero << endl;

    cout << "## Enter 1 to go again, 0 to exit: "; cin >> flag ; cout << endl;

    }

    return 0;
}

出于某种原因,我得到了非常奇怪的输出。任何人都可以帮助我,例如:

## Please enter a #: 245
## Even numbers: 3
## Odd Numbers: 13
## Zeros: 0
## Enter 1 to go again, 0 to exit: 1

## Please enter a #: 342
## Even numbers: 5
## Odd Numbers: 14
## Zeros: 0
## Enter 1 to go again, 0 to exit: 

2 个答案:

答案 0 :(得分:1)

您将相同的计数器变量通过引用传递给您的函数lab14,而不会在后续调用之间将它们重置为零。这意味着下次调用该函数时,计数永远不会被重置,因此除了第一个函数调用之外,总计还会继续构建,从而给出不正确的值。

添加

even = 0;
odd = 0; 
zero = 0;
cout调用重置变量后,在循环结束时

。或者,在lab14循环之前将其归入while函数内。

顺便提一下,你在该功能中有3个返回声明 - 其中2个永远不会到达。

答案 1 :(得分:1)

你在这里。

#include <iostream>

void lab14( unsigned long long int num, unsigned int &even, unsigned int &odd, unsigned int &zero )
{
    const unsigned long long Base = 10;

    even = odd = zero = 0;

    do
    {
        long long int digit = num % Base;

        if ( digit % 2 != 0 ) ++odd;
        else digit == 0 ? ++zero : ++even;
    } while ( num /= Base );        
}

int main()
{
    std::cout << "#############################" << std::endl;
    std::cout << "## Even, odd, zero counter " << std::endl << std::endl;;


    while ( true )
    {
        std::cout << "## Please enter a # (0-exit): "; 

        unsigned long long int num = 0;
        std::cin >>num;

        if ( !num ) break;

        unsigned int even, odd, zero;

        lab14( num, even, odd, zero );

        std::cout << "## Even numbers: "<<  even << std::endl
                  << "## Odd Numbers: " << odd << std::endl
                  << "## Zeros: " << zero << std::endl;

        std::cout << std::endl;            
    }

    return 0;
}

如果要输入

123456789012345678 

然后

0

然后输出

#############################
## Even, odd, zero counter 

## Please enter a # (0-exit): 123456789012345678
## Even numbers: 8
## Odd Numbers: 9
## Zeros: 1

## Please enter a # (0-exit): 0

至于你的函数,我认为它太复杂了三个return语句:)

return odd;
return even;
return zero;

它们足以支持三个独立的功能。

至于我,然后我决定该函数不需要return语句。