![](/img/trans.png)
[英]A program that reads integers as long as they are alternately positive and negative. C++
[英]C++ ,Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers
“計算正數和負數並計算數字的平均值編寫一個程序,讀取未指定數量的整數,確定讀取了多少正負值,並計算輸入值的總數和平均值(不計算零)。你的程序以輸入 0 結束。將平均值顯示為雙精度。我哪里出錯了??
#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;
}
您可以使用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;
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.