The main function shoud pass to another function a float array and an integer indicating the size of the array and return the average of all the numbers in the array. How would I pass the array to my division function, add the sum of the numbers in the array and get the average. I can get this to work all when I add the sum in main and just divide the sum/size in the division function, but when I try doing it in the function I cant get it to work.
If I added the sums of the array in the main function then called the division function and just sum/size.... it worked. When passing the float array to the division function then adding their sums and dividing by size. It has not worked. I made a few changes to it as seen below and now it is working but this is the way off. Say I want to enter 3 numbers and find their average. I enter 3, 3, 3... which obviously the average is 3. I now get 1. #QNAN instead of 3.
In what compiler will this even compile in the first place? It is not legal to have a non-constant value for an array size...line 7 should cause a compiler error. And even if there was a compiler plugin/extension, size is still undefined when the array is created, so the array could be any size, even large enough to throw an exception.
first of all......even if compiler doesn't give error while compiling this code , your code is incorrect.....and i tell you why.....
you have float array[size]......if you work on linux its all right but on windows it must be give error because on linux compiler takes memory from dynamic memory.......
second) your size isn't initialized so it contains garbage......so you had better do this....
float array[30] and then input your size.....30 for reserve.....
and finally in your division function you write
float sum;
and you didn't initialize it...........write float sum=0;
1) In division( ), sum is used without initialization( potential undefined behavior when used ).
2) sum in main( ) is unused( compiler warning ), and uninitialized.
3) size in main( ) is used before initialization( potential undefined behavior ).
4) size isn't checked for a negative numerical value before declaring array with it( potential undefined behavior ).
5) Use of system( ) causes the program to become OS dependent. Use std::cin.get( ) instead.
Thank you for all your replies but I ended up getting it to work afterall before seeing all these replies. The code works now.
1. Mainly I was getting the garbage answer after compiling because sum was not initialized. So when I tried to return it... it got garbage.
2. The other problem was that I was trying to return the sum instead of the average.
3. On Windows it is possible to have a non-constant value for the array size. I could have done... array[100] or any number but I want to make the array only as big as the number the user wanted to store for. I had to swap the location of where I declared the array putting it after a size was cin.