"计算正数和负数并计算数字的平均值编写一个读取未指定数量的整数的程序,确定读取了多少正值和负值,并计算输入值的总和和平均值(不包括零)。您的程序以输入0结束。将平均值显示为double。我哪里出错?
#include <iostream>
using namespace std;
int main()
{
int num= 0;
int sum=0;
int pos=0;
int neg=0;
double ave=0;
cout << "Enter an integer, the input ends if it is 0: " ;
cin >> num ;
if (num%10==10) {
while (num!=0) {
num/=10;
if (num%10>0) {
pos++;
}
else if (num%10<0) {
neg++;
}
sum+=num;
}
ave= (double)sum/(pos+neg);
}
cout <<"The number of positives are " << pos <<endl;
cout <<"The number of negatives are " << neg <<endl;
cout <<"The total is " << sum << endl;
cout <<"The average is "<< ave << endl;
return 0;
}
答案 0 :(得分:0)
您可以使用char[]
来阅读输入。
我修改了你的程序如下;
int main()
{
int sum=0;
int pos=0;
int neg=0;
double ave=0;
char arr[100] = {'\0',};
std::cout << "Enter an integer, the input ends if it is 0: " ;
gets(arr);
int index = 0;
char ch[1];
bool negativeNumber = false;
while(true)
{
ch[0] = arr[index++];
if(ch[0] == ' ') // Check space and continue;
{
continue;
}
else if(ch[0] == '0' || ch[0] == '\0') // check for 0 or NULL and break;
{
break;
}
if(ch[0] == '-') // Set flag if "-ve"
{
negativeNumber = true;
continue;
}
int digit = atoi(ch);
if(negativeNumber)
{
digit *= -1;
negativeNumber = false;
}
if(digit > 0)
{
pos++;
}
else if(digit < 0)
{
neg++;
}
sum += digit;
}
ave= (double)sum/(pos+neg);
cout <<"The number of positives are " << pos <<endl;
cout <<"The number of negatives are " << neg <<endl;
cout <<"The total is " << sum << endl;
cout <<"The sverage is "<< ave << endl;
return 0;
}
希望这有帮助。