Back to General discussions forum
Hey. Im having an error trying to round numbers to the next integer. What's wrong with this code? Thanks for the help
#include <stdio.h>
#include <math.h>
int main() {
int N;
int vector[500];
int total = 0;
scanf("%d", &N);
fflush(stdin);
for(int f = 0; f < N; f++) {
int i = 0;
int j = 1;
while (j != 0) {
scanf("%d", &vector[i]);
total += vector[i];
if (vector[i] == 0) {
j = 0;
}
i++;
}
float total2;
total2 = (total / (i - 1) ) ;
float result = (total2 - floor(total2) > 0.5) ? ceil(total2) : floor(total2);
printf("%.0f ", result);
total = 0;
}
}
a) Your indentation needs improving!
b) With total2 = (total / (i - 1) ) ;
I'd expect you to be dividing by the number of elements in the array, which is N. Why divide by i-1?
c) With that same line, when total=99 and i=5, the division will be 99/4. What are you expecting total2 to contain?
What does total2 contain?
total2 is the final number,its division of all the elements that are in the array, divided by the number of inserts(excluding zero)
In this exercise, N is not the number of elements that they'll put. It's the number of times i'll have to the the calculations. That's why I use (i-1).
When total=99 and i=5, the division will be 99/4. What value are you expecting total2 to contain? What value does total2 contain?
If i = 5, then i've put in 5 numbers, including 0, that should not be included in the calculations (that's why i - 1). And total = 99, should be the sum of the integers in the array, excluding 0; So, total2 should be: total / (i - 1), that will be the average of the array.
float total2 = (total / (i - 1) )
If I'm not mistaken, on the right side all variables are integer, so you are doing integer division, not float here.
E.g. if total
is 100 and you divide by 99, you get pure zero. You need typecast here, I think.
Also you'd better use double instead of float. Floats make sense only when we utterly need to save memory. They are too short... :)
Ohh, that worked! Thank you, Rodion and Quandray. The only think that i still dont understand is: Why this works?
double result = (int)(total2 - floor(total2) > 0.5) ? ceil(total2) : floor(total2);
Why can't I just use? They're not the same?
int result = (total2 - floor(total2) > 0.5) ? ceil(total2) : floor(total2);
Thank you all for the help!