gpt4 book ai didi

c++ - 计数器的问题

转载 作者:行者123 更新时间:2023-11-30 01:45:21 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com