I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = i) {
cout << "Please input a number: ";
cin >> input;
total = total = input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i
in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
CodePudding user response:
you don't need the
for loop
, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use acounter
variable instead.also, you are breaking in the loop without checking if the
input < 0
, so you can write thisif (input < 0) break;
also, you shouldn't calculate
av_number = total / counter;
except only after the end of the bigwhile
loopit's
total = input;
nottotal = total = input;
writing
while (input >= 0)
wouldn't make sense as long as you are breaking inside the loop wheninput < 0
, so you can writewhile (true);
instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter ;
total = input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
CodePudding user response:
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total
.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input && !(input < 0.f); i)
{
// now `input` is non-negative
total = input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}