编写程序以显示奇数和偶数

时间:2018-12-31 05:28:34

标签: c++ visual-c++

我试图写这段代码,但我做不到 q是: 通过使用for循环,编写一个程序以接收任意5个数字的输入,并显示偶数的总数。输出应如下图所示

---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------

这就是我所做的:

    #include<iostream>
using namespace std;
int main()
{
    int i,j=0,c=0;

    for(i=0;i<5;i++)
    {
        cout<<"enter 5 numbers "<<i ;
        cin>>i;
    }
        if(i==0)
        {
        cout<< "0 is not even number"<<endl;
        }
        else if(i%2==0)
        {j++;}
        else if(i%2 !=0)
        {c++;}


    cout<<"total exists even : "<<j<<endl;
    cout<<"total exists ODD : "<<c<<endl;   
return 0;
}

5 个答案:

答案 0 :(得分:1)

逐步检查代码(请注意格式更改!)

#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
    int i, j=0, c=0;

    for(i = 0; i < 5; i++)
    {
        cout << "enter 5 numbers " << i;
        cin >> i; // you are overwriting your loop variable!!!
                  // how do you think your program will go on if you enter
                  // e. g. 7 right in the first loop run?
                  // additionally, you did not check the stream state afterwards
                  // if user entered something invalid (e. g. S), cin sets the
                  // fail flag and stops further reading - attemps doing so yield
                  // 0 (since C++11) or don't modify the variable (before C++11)
    }

    // this section is outside the loop already!
    // so you are only checking the number you read in your loop in the very last run
    if(i == 0)
    {
        cout << "0 is not even number" << endl;
    }
    else if(i % 2 == 0)
    {
        j++;
    }
    // this check is redundant: it is the complement to your previous
    // check, so if the first went wrong, the second cannot be false any more
    // (compare: you did not check for i != 0 either before doing the modulo check)
    else /* if(i % 2 != 0) */
    {
        c++;
    }

    cout << "total exists even: " << j << endl;
    cout << "total exists odd:  " << c << endl;   
    return 0;
}

更改的代码:

#include<iostream>

int main()
{
    // several serious coding guide lines mandate: only one variable per line:
    unsigned int odd = 0;
    unsigned int even = 0;
    // I used unsigned int here, negative counts are just meaningless...
    // I'm consequent in these matters, but range of (signed) int suffices anyway,
    // so you can use either one...

    // C++ is not C (prior to C99) - keep scope of variables as local as possible
    // (loop counter declared within for header, local variable within body)
    for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
    {
        std::cout << "enter 5 numbers (" << i << "): ";
        int n; // separate variable!
        if(!(std::cin >> n))
        {
            // some appropriate error handling!!! e. g.:
            std::cout << "invalid value entered";
            return -1;
        }

        // this now resides INSIDE the for loop
        if(n == 0)
        {
            cout << "0 is not even number" << endl;
        }
        else
        {
            // this is an ALTERNATIVE calculation

            n %= 2;    // gets either 0 or 1...
            odd += n;
            even += 1 - n;

            // (I personally prefer avoiding conditional branches but you *can*,
            //  of course, stay with the if/else you had before, too...
            //  - just don't check the complement as shown above)
        }
    }

    cout << "total exists even: " << even << endl;
    cout << "total exists odd:  " << odd  << endl;   
    return 0;
}

关于未签名的:有时这些是有好处的:

void f(int n)          { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }

但有时必须谨慎处理:

for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;)   { /* ... */ } // correct variant

(第一个会使用 signed int,但不是unsigned type 的错,而是程序员没有选择正确类型的错为他或她的意图...)。

仅出于完整性考虑:假设我们可以删除数学上不正确的陈述,即零甚至不是零,那么我们可以更简单地做到这一点:

unsigned int constexpr LoopRuns = 5u;

int main()
{
    unsigned int odd = 0; // just one single variable...

    for(unsigned int i = 0; i < LoopRuns; i++)
    {
        std::cout << "enter 5 numbers (" << i << "): ";
        int n;
        if(!(std::cin >> n))
        { /* ... */ }

        odd += n %= 2;
    }

    // one single difference instead of five additions...
    cout << "total exists even: " << LoopRuns - odd  << endl;
    cout << "total exists odd:  " << odd             << endl;   
    return 0;
}

答案 1 :(得分:0)

该程序将为您提供帮助。

#include <iostream>
int main () {
    int num[5], even = 0, odd = 0;
    bool hasZero = false;
    std::cout << "Enter 5 numbers:"
    for (int i = 0; i < 5; i++) {
        std::cin >>  num[i];
    }

    for (int i = 0; i < 5; i++) {
        if (num[i] == 0) { // Checking if the current number is zero
            hasZero = true;
        } else if (num[i] % 2 == 0 ) { // Checking if the current number is even
            ++even;
        } else { // If the number is not even, then it must be odd
            ++odd;
        }
    }

    if (hasZero) { // If the input has zero then print following statement
        std::cout << "0 is not an even number" << std::endl;
    }

    std::cout << "Total even count: " << even << std::endl;
    std::cout << "Total odd count: " << odd << std::endl;

    return 0;
}

如果您听不懂任何内容,那么下面的评论部分将非常欢迎您!)


您的代码有问题:

  • for语句中,counter和input使用相同的变量,即i。这样既不会正确执行for循环,也不会正确捕获输入。

  • 每次输入任何内容都会覆盖i变量,那么只有最后一个输入(5个输入中的 )将存储在内存中。

  • 您正在使用if statement检查最后一个输入,因为循环之前已经结束。


如果您希望代码正常运行,则可以进行以下修改:

#include<iostream>
using namespace std;
int main()
{
    int num,j=0,c=0;  // Change the name to num here, because i will be used later as a counter variable.

    for(int i=0;i<5;i++)
    {
        cout<<"enter 5 numbers "<<i ;
        cin>>num;

        // Don't end for loop here, this will not allow every input to be checked.

        if(num==0)
        {
            cout<< "0 is not even number"<<endl;
        }
        else if(num%2==0)
        {
            j++;
        }
        else if(num%2 !=0)  // Or just add a *else* here instead of *else if*, they will work exactly the same here.
        {
            c++;
        }

    } // End of for loop

    cout<<"total exists even : "<<j<<endl;
    cout<<"total exists ODD : "<<c<<endl;   
    return 0;
}

答案 2 :(得分:0)

首先,0 是一个偶数,并且代码需要适当缩进,这样您就可以看到您确实将输入读入一个整数,该整数也可以控制循环,并且您的if语句位于for循环之外(尽管缩进具有误导性。这是一个简单的示例实现,但是您可以(并且应该)修复我在自己的代码中指出的错误:

#include <iostream>
int main() {
  std::cout << "Enter 5 numbers\n";
  int cnt(5);
  int n, odd(0), even(0);
  while(cnt-- && (std::cin >> n))
    n % 2 ? ++odd : ++even;

  std::cout << odd << " odd, "
  << even << " even numbers" << std::endl;
  return 0;
}

请注意递减和&& short-circuits的事实。

答案 3 :(得分:0)

这应该是您的代码: 您采用一个整数数组来存储输入值。前往https://www.tutorialspoint.com/cprogramming/c_arrays.htm以了解更多的abour数组。

#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
    cout<<"enter 5 numbers "<<i ;
    cin>>numbers[i];
}
for(i=0;i<5;++i){
    if(numbers[i]==0)
    {
    cout<< "0 is not even number"<<endl;
    }
    else if(numbers[i]%2==0)
    {j++;}
    else if(numbers[i]%2 !=0)
    {c++;}
}

cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;   
return 0;
}

答案 4 :(得分:-1)

using namespace std;

int main()
{
    int * Array = new int[5];
    int even(0), odd(0);    
    for(int i = 0; i < 5; i++)
    {
        cout<<"enter "<< i+1 << "-th number: " << flush;
        cin>>Array[i];
        if(!Array[i]) 
        {
        cout<< "0 is not even number... input again"<<endl;
        i = i-1;
        }
        else
        {
            if(Array[i]&1) odd++;
            else even++;
        }
    }
    cout<<"total exists even : "<<even<<endl;
    cout<<"total exists ODD : "<<odd<<endl;   
    cin.get(); cin.get();
    delete[] Array;
    return 0;
}