Array division problem

Write a complete C program that will fill an array with int values read in from the keyboard, one per line, and outputs their sum as well as all the numbers read in, with each number annotated to say what percentage it contributes to the sum. Your program will ask the user how many integers there will be, that will determine the length of the array.
Sample Output:
How many integers will you enter?
4
Enter 4 integers, one per line:
2
1
1
2
The sum is 6.
The numbers are:
2 which is 33.33% of the sum.
1 which is 16.67% of the sum.
1 which is 16.67% of the sum.
2 which is 33.33% of the sum


I'm having problems with the division of arrays and instead of getting the percentage I only get 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h>
#include<conio.h>
int main()
{
	int x,n,s=0,a;
	float y;
	printf("How many integers will you enter? \n");
	scanf("%d",&n);
	printf("Enter %d integers, one per line\n",n);
	int num[100];
	for(x=0;x<n;x++)
	{
		scanf("%d\n",&a);
		num[x]=a;
		s+=num[x];
	}
	printf("The sum is = %d\n",s);
	printf("The numbers are:\n");
	for(x=0;x<n;x++)
	{
		num[x]=a;
		y=(a/s)*100;
		printf("%d which is %f % of the sum\n",num[x],y);
	}
	getch();
	return 0;
}
Last edited on
Change
y=(a/s)*100;
to
y=(a*1./s)*100;
@skaa's solution is perfectly good, but maybe he hasn't explained the source of the problem for next time: integer division. Divide one integer by another (here a and s) and the answer is (in most decent programming languages) ... an integer. So it would round towards zero, giving, in this instance, 0.

His solution - and there are lots of alternatives - is to carry out an operation (in this case, multiplying by 1.0) which forces one participant to become a floating-point number before the division instead.

Just watch out for it - it happens a lot for countable quantities. And it's true in most programming languages (but probably not on your calculator).
Topic archived. No new replies allowed.