Write a program that finds the average of several floats. allow the user to specify how many values that will be entered. limit number count to 20

StackOverflow https://stackoverflow.com/questions/18025526

  •  21-06-2022
  •  | 
  •  

Question

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string num[21];
    int amount_num;

    cout<< "How many numbers do you want? (max 20)\n";
    cin>> amount_num;

    if (amount_num<= 0 || amount_num >= 22)
    {
        cout << "Invalid size.  Ending.\n";
    }
    for (int counter =0; counter < amount_num; counter++)
    {
        cout<< "Enter vaule "<< counter<< ":"<< endl;
        cin>> num[counter];
    }

    for(int t= 0; t< amount_num; t++)
    {
        int total;
        int average;
        total = total + num[t];
        average= total/ t;
        cout<< "Average: "<< average<< endl;
    }
    for(int x=0; x< amount_num; x++)
    {
        cout<< "You entered:"<< endl;
        cout<< num[x]<< endl;
    }
}

An error keeps popping up when I try to add the total plus num[t]. It states: error no operator+ in total+ num[t].

Was it helpful?

Solution

Several things:

  1. You are using an array of string, you should use array of float.
  2. If you want average of float then variable total should be float instead of int

OTHER TIPS

You may want to move

int total;
int average;

before your loop and

average= total/ t;
cout<< "Average: "<< average<< endl;

after the loop otherwise you will just keep redefining you variables and that will just break your code. Also you should declare the variable total and average as 0. You compiler should already be warning you about this.

If you do that you will end up with a code looking like this:

int total = 0;
int average;

for(int t= 0; t< amount_num; t++)
{
    total = total + num[t];
}
average= total/ amount_num;
cout<< "Average: "<< average<< endl;

that should fix the problem you are having with it returning multiple results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top