0

Program doesnt work (sometimes)

hello, my task is to enter "n" numbers and then output the average and the number closest to the average, i have done it with vector but program doesnt work half of the time, can you help me. thanks. https://code.sololearn.com/cm2aW6VkcXdO/?ref=app

19th Oct 2018, 5:38 AM
Salt MyMan
Salt MyMan - avatar
4 odpowiedzi
+ 2
Nevermind then, that means the mistake is in the second part, more precisely in line 29. You didn't use curly braces around the body of your if-statement. That means that the compiler only sees one single statement as the body of that if-statement, so the line 'f=h;' is not part of the if-statement, even if it in the same line.
19th Oct 2018, 7:10 AM
Shadow
Shadow - avatar
+ 2
I couldn't find a case where it doesn't work, so I'm just guessing right now, but I think it sometimes fails because 'z' is not initialized and therefore has some garbage value that is not necessarily 0. You should initialize it to 0 before adding stuff to it. On a sidenote: I would encourage you to a) avoid global variables when possible (its considered bad practice) and b) give your variables meaningful names. 'sumOfInputs' instead of a simple 'z' or 'average' instead of 'p' for example. It will make your code more readable and help others understand it.
19th Oct 2018, 6:42 AM
Shadow
Shadow - avatar
+ 1
5, 2, 4, 7, 10, 1,      1, 4.8 this is the example when it doesnt work, and thank for advice ill try it
19th Oct 2018, 6:54 AM
Salt MyMan
Salt MyMan - avatar
0
thanks a lot man
19th Oct 2018, 7:43 AM
Salt MyMan
Salt MyMan - avatar