#include <iostream>
usingnamespace std;
int main()
{
double sum_pos = 0, sum_neg = 0,num[10],numneg[10],numpos[10],mean = 0;
int i;
for(i=0;i<10;i++){
std::cout << "Enter a number:";
std::cin >> num[i];
if (num[i] > 0)
sum_pos = sum_pos + num[i];
if (num[i] < 0)
sum_neg = sum_neg + num[i];
}
cout << "The sum of the positive numbers is: " << sum_pos << endl;
cout << "The average of the positive numbers is: " << (sum_pos/num[i]) <<endl;
cout << "The sum of the negative numbers is: " << sum_neg << endl;
cout << "The average of the nonpositive numbers is: " << (sum_neg/num[i]) <<endl;
}
I think your average values are a bit off. The average for negative numbers is the sum / number of negative numbers. Same with positive not the sum of each type / total of all numbers. Also you are incrementing number by 2 each time. Maybe you meant braces around your if statements? Either way if its not greater than 0 it has to be less than or equal so you can simply use an else statement and then after adding to the sum you can simply increment the count by 1.
1 2 3 4 5 6 7
if (number > 0)
sum_greater_than_zero = sum_greater_than_zero + number;
number++;
if (number < 0)else
sum_less_than_zero = sum_less_than_zero + number;
number++;
Fixes the second issue addressed now for the first you will want two more variables. int positiveNumbers = 0 , negativeNumbers = 0;
cout << "The average of the positive numbers is: " << (sum_greater_than_zero/positiveNumbers) <<endl;
cout << "The average of the nonpositive numbers is: " << (sum_less_than_zero/negativeNumbers) <<endl;
Keep in mind you are doing integer division also I would suggest you use double division if you want more accurate results. 1 / 2 = 0 with ints 1.0 / 2.0 = 0.5 with doubles. It floors ( rounds down ) it in other words .99999 in int is considered 0.
#include <iostream>
usingnamespace std;
int main()
{
double sum_greater_than_zero = 0, sum_less_than_zero = 0,num[10];
int i;
int positiveNumbers = 0 , negativeNumbers = 0;
for(i=0;i<10;i++){
std::cout << "Enter a number:";
std::cin >> num[i];
if (num[i] > 0) {
sum_greater_than_zero = sum_greater_than_zero + num[i];
++positiveNumbers;
}
else
{ sum_less_than_zero = sum_less_than_zero + num[i];
++negativeNumbers;
}
}
cout << "The sum of the positive numbers is: " << sum_greater_than_zero << endl;
cout << "The average of the positive numbers is: " << (sum_greater_than_zero/positiveNumbers) <<endl;
cout << "The sum of the negative numbers is: " << sum_less_than_zero << endl;
cout << "The average of the negative numbers is: " << (sum_less_than_zero/negativeNumbers) <<endl;
}