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.
#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= newint[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= newint[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.