Problem with average calculator, help me out?

Started by
8 comments, last by Dragonsoulj 8 years, 10 months ago

HEY GUYS!!!!

8D so im learning C++ on my own and i signed up for game institutes 5 year program thing. o u o

so i basically have just me and a textbook to learn from and one of the exercises is to make a average calculator and i sorta figured out how to do it using a for loop. P: but theres a problem. e.e

its not stopping when its supposed to. it just keeps going. and its really irritating meeeeeee

D8 help me out here guyzzzzz

it wont perform as intended past 2. if you input 2 as the amount of numbers you want. then it will do the job. but if you put in 4. the loop keeps going on and on. and never ends. e.e and then i get some sorta error saying the stack is corrupt.

I also tried using a break statement, but same thing e.e it just ignores it and keeps looping


#include <iostream>
#include <string>

using namespace std;
//average calculator

int main()
{
	int a;
	float avrg[]{1};
	float quo = 0;
	cout << "Enter the amount of numbers youre going to average: ";
	cin >> a;

	for (int x = 0; x < a; )
	{

		cout << "[" << x << "] = ";

		cin >> avrg[x];
		quo += avrg[x];
		x++; // put this here to see if it would make a difference.


	}

	cout << "Average = " << quo/a;

	cin >> a; // just here to pause program in console window
}
Advertisement

Weird. I can't spot the problem for certain, but my guess is that you're accidentally overwriting some of your other variables in memory.

This line:


float avrg[]{1};

Creates an array of only a single variable in length. Though I'm not sure how that's compiling - I think it requires an equal sign between the [] and the {1}.
([Edit:] Huh, well it compiles in GCC 4.9.2 as well, so I guess it's valid syntax after all. wacko.png)

Anyway, it's an array with only a single element in it.

But here in your loop:


cin >> avrg[x];
quo += avrg[x];

...you keep on accessing the x'th element, and since 'x' is equal to and greater than 1 for every iteration except the first iteration of the loop, this means you are writing and reading invalid memory outside of the array. That's not good. mellow.png

I think your infinite looping is basically an accident coming out of writing data to the wrong locations in memory.

[Edit 2:] Uh, yeah, this is exactly what's happening, since that's what the pop-up error message is warning you about. I didn't read the message. *facepalm*

You don't even need an array - you just need a temporary variable instead:


float value = 0.0f;
cin >> value;
quo += value;

Also, as a general safety rule, you should always initialize your variables when you create them.


int a; <--- This should be initialized to zero.

Though this isn't causing any problem in your current code.

You need to reserve enough floats to store user input. Either dynamically allocate an array large enough to hold the number of floats the user requested, or use a stack based array, and limit the maximum number the user can enter.

If you declare the array as the variable input:


float avrg[a];

You will get an array that can hold a+1 floats a floats. Since you need to know a, place this after you get your a value. See if that helps you any.

Edit: So future readers don't get confused.

@Servant I think the


float avrg[]{1};

works in C++11. My compiler mentions it as a warning.

In an older pre-C++11 GCC version, it gives a syntax error, so you're probably right about that.

It's probably part of uniform initialization then - I haven't really used uniform initialization all that much, so far.

Why are you even using an array, when those values are never used again after adding them to the sum you misnamed quo?

If you declare the array as the variable input:


float avrg[a];
You will get an array that can hold a+1 floats.


No, it will not. The whole point of the convention that array indices are number from 0 has the advantage that there are never any "+1"s to think about. `float avrg[a]' will get you an array that can hold `a' floats.

#include <iostream>
#include <string>

using namespace std;
//average calculator

int main()
{
	int a = 0;
	float tmp = 0.0f;
	float quo = 0.0f;
	cout << "Enter the amount of numbers youre going to average: ";
	cin >> a;

	for (int x = 0; x < a; ++x )
	{
		cout << "[" << x << "] = ";
		cin >> tmp;
		quo += tmp;
	}
        quo /= a;
	cout << "Average = " << quo;
        
	cin >> a; // just here to pause program in console window
}

writing over useless array's bounds corrupted stuff?

My own version. The main differences are:
* No `using namespace std'. I prefer to let standard names stand out with their `std::'.
* Better variable names. This is important! Also, a variable's meaning never changes (unlike `quo' in the original code, which is the running sum for a while and then it's the average).
* Variables are introduced when needed, and never initialized with values that are never used.
* Nothing to stop the console window from closing. This is not your program's responsibility. Command line programs don't usually pause for input at the end of their run. If your IDE does this annoying thing of closing the window without giving you a chance to see the result, try to see if it can be configured to not do that. Or you can run the program from an existing window.

#include <iostream>

int main() {
  std::cout << "Enter the amount of numbers you are going to average: " << std::flush; // Without flush the output might be buffered
  int n;
  std::cin >> n;
  
  float sum = 0.0f;
  
  for (int i = 0; i < n; ++i) {
    std::cout << '[' << i << "] = " << std::flush;
    float value;
    std::cin >> value;
    sum  += value;
  }
  
  float average = sum / n;
  std::cout << "Average = " << average << '\n';
}

If you declare the array as the variable input:


float avrg[a];
You will get an array that can hold a+1 floats.


No, it will not. The whole point of the convention that array indices are number from 0 has the advantage that there are never any "+1"s to think about. `float avrg[a]' will get you an array that can hold `a' floats.

Apologies. Clearly I have been working in VB for far too long lately.

This topic is closed to new replies.

Advertisement