0

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!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    What's the goal of your `for`? And why are you adding to `total` before checking whether `input` is negative? – Stephen Newell Oct 04 '22 at 16:46
  • So you want to write a program that takes all the numbers but only calculates the average for the positive numbers? – Mahdy.n Oct 04 '22 at 16:47
  • 1
    `for (int i = 1; i >= 1; i = ++i)` how did you come up with this loop? Are you obfuscating code? – Marek R Oct 04 '22 at 16:54
  • Input into [std::vector](https://en.cppreference.com/w/cpp/container/vector) and use [std::views::filter](https://en.cppreference.com/w/cpp/ranges/filter_view) to generate the output. In general in C++ try to avoid [raw loops] (https://sean-parent.stlab.cc/presentations/2013-09-11-cpp-seasoning/cpp-seasoning.pdf) by Sean Parent. This might require you to learn about [lambda functions](https://en.cppreference.com/w/cpp/language/lambda) as well. – Pepijn Kramer Oct 04 '22 at 16:57
  • Looks like your `for` is looping forever, or until the world ends, or your `i` overflows. You test `i >= 1` will ways be true unless you decrement your `i` variable. – Thomas Matthews Oct 04 '22 at 19:41

2 Answers2

0

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';
    }
}

The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0
  • 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 a counter variable instead.

  • also, you are breaking in the loop without checking if the input < 0, so you can write this

    if (input < 0)
         break;
    
  • also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop

  • it's total += input; not total = total += input;

  • writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (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?

abdo Salm
  • 1,678
  • 4
  • 12
  • 22
  • You used namespace std yourself !! – Mahdy.n Oct 04 '22 at 17:05
  • Appreciate the help. I included namespace std because I'm a student, and we were told to use it for now. Taking a look at the post you linked, I see what you're getting at though. Thanks again for helping me sort through that little mess, worked great after the changes you suggested. – Beetle_Soft Oct 04 '22 at 17:14
  • @Beetle_Soft A word of caution: This solution does not check that extracing a number actually succeeds so if the user decides to press CTRL-D (*nix) or CTRL-Z (Windows) instead of entering a negative number, the program will most likely enter an endless loop. – Ted Lyngmo Oct 04 '22 at 17:17
  • @TedLyngmo That's a good point. I'll take some time to implement a failsafe. Appreciate it! – Beetle_Soft Oct 04 '22 at 17:22
  • @Beetle_Soft You're welcome. You can see how it can be done in my answer. `if(std::cin >> input) { /*success*/ } else { /*failure*/ }` About `using namespace std;` and _"we were told to use it for now"_ - I wish the teacher would have done it the other way around: Not mentioning that one can do `using namespace ...` until showing you when you _should_ actually do `using namespace std;`. – Ted Lyngmo Oct 04 '22 at 17:25