Printf Problem.

The code is below. The problem is to interview a no. of people about their foot size and then print out how many people have xx foot size and how many people out of total people have it. I have managed to get the accurate results, but my way is wrong in that it will print out the result for every array element, so if 2 people have the same foot size, it will be printed out twice. I need to like see if a specific value has been found before, then don't print out the result as it has already been printed, but whatever I tried to do, would lead me to nothing getting printed. I can't think of any idea, so if anyone could give me a solution I'd appreciate it.


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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"

int poll(int *myarray, int n);

int main()
{
int n;
printf("Input the size of the array:\n");
scanf("%d", &n);					
int *myarray; 
myarray= new int[n];
printf("input the %d array elements now: \n", n);
for (int i=0; i < n; i++)		{
scanf("%d", &myarray[i]);	} 
poll(myarray, n);
getch();
return 0;
}

int poll(int *myarray, int n)						
{
	int i, j, nr;
	float counter = 0;
	float temp = n;
	float percentage; 
	
	for (i=0; i<n; i++)
	{
		for (j=0; j<n; j++)
		{
			if (myarray[j] == myarray[i])
			{
				counter++;
			}
		}
		

		percentage = counter / temp * 100;
		printf("A size foot of %d belongs to %.0f people \n", myarray[i], counter);
		printf("The percentage of a size foot of %d is %.3f%%  \n\n", myarray[i], percentage);
		counter = 0;
}
	return 0; 
}
The main problem I have with you r code is the mixing of C & C++.

I see all the printfs and think it is a C program, then I come across this:

myarray= new int[n];

In C, you cannot specify the size of an array at runtime, you are trying to get around this by using dynamic memory allocation with C++ operator new.


Why not make it a proper C++ program:

- Use cin and cout instead of scanf & printf.
- Use the STL <vector> which is like a automatically re-sizeable array. Use push_back to put things into the vector.

Read about vectors here:

http://www.cplusplus.com/reference/stl/vector/


There is a lot of good stuff in the reference / documentation section of this page.

As for your actual problem, it could be to do with the placement of the braces in the for loops at the end.

HTH


Topic archived. No new replies allowed.