Can someone help me with my code? The prompt is Design a program that contains a loop that asks the user to enter a series of positive numbers.The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum
#include <iostream>
usingnamespace std;
float loopCalculateSum(float sum);
void showResults();
int main()
{
//Inititalize variable
float sum = 0;
// Call to loop function
sum = loopCalculateSum(sum);
//Delay
char quitKey;
cout << "Press any key and Enter to end program: ";
cin >> quitKey;
//End of Program
return 0;
}
// Loop function
float loopCalculateSum(float sum)
{
int userInput = 0;
do {
cout << "Enter a postive number" << endl;
cin >> userInput;
sum = sum + userInput;
cin >> sum;
userInput++;
} while (userInput >= 0);
return sum;
}
Your problem is that you are adding input before checking its sign. Also you reading into sum for some reason.
1 2 3 4 5 6 7 8 9 10
//Strongly prefer double to float
double loopCalculateSum(/*you do not need argument here*/)
{
//Why there was int? Either have int as return type too or make input floating point
double input;
double sum;
while(std::cin >> input && input >= 0)
sum += input;
return sum;
}