我是C++的新手,并有工作要编辑此代码以使其起作用。由于某些原因,当我使用多个正数或负数的组合时,它为我输入多个数字的答案提供了一个额外的数字。

例:

我输入3个正数和1个负数。计数器显示4个正数和1个负数。如果我从负数开始而不是正数,也会发生同样的事情。

任何帮助将不胜感激。这是代码:

#include <iostream>
using namespace std;

int main()
{
    int number   = 0;
    int positive = 0;   //counter
    int negative = 0;   //counter
    int totalPositive = 0;
    int totalNegative = 0;

    //get a number
    cout << "Enter a positive or negative integer (enter 0 to end): ";
    cin >> number;

    while (number != 0)
    {
        //update counters
        if (number > 0)
        {
            positive =+ 1;
        }
        else
            negative =+ 1;

        //end if

        //get another number
        cout << "Enter another positive or negative integer (enter 0 to end): ";
        cin >> number;
        totalPositive += positive;
        totalNegative += negative;
    }//end while

    //display counters
    cout << endl;
    cout << "Total positive numbers: " << totalPositive << endl;
    cout << "Total negative numbers: " << totalNegative << endl;

    system("pause");
    return 0;
}   //end of main function

最佳答案

试试这个代码:

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int number;
    int positive = 0;
    int negative = 0;

   do{

        cout << "Enter a positive or negative integer (enter 0 to end): ";
        cin >> number;

        if (number > 0)
           positive += 1;

        else if(number<0)
           negative += 1;


    }while(number!=0);
    //end while

    //display counters
    cout << endl;
    cout << "Total positive numbers: " << positive << endl;
    cout << "Total negative numbers: " << negative << endl;

    system("pause");
    return 0;
}   //end of main function

您无需使用total positivetotal negative,除非您希望对正数和负数求和。

关于c++ - 柜台麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34778984/

10-11 17:06