Need some basic C++ help
Mar 22, 2012 at 1:33am UTC
I have a problem to solve, that sorts the 10 worst players basing on the sum of their POINTS. (
poenik +
poenis )
This is the whole code:
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include <iostream>
using namespace std;
struct lizgacka
{
char ime[40];
int br;
char drzava[2];
float poenik;
float poenis;
};
void zapisi(lizgacka a[],int i)
{
for (int j=0;j<i;j++)
{
cout<<"Ime i Prezime:" <<endl;
cin>>a[i].ime;
cout<<"Tricifren starten broj:" <<endl;
cin>>a[i].br;
cout<<"Drzava:" <<endl;
cin>>a[i].drzava;
cout<<"Poeni od kvalifikacii:" <<endl;
cin>>a[i].poenik;
cout<<"Poeni od slobodna programa:" <<endl;
cin>>a[i].poenis;
}
}
void pechati(lizgacka a[],int z)
{
int x;
cout<<"10-Wors players are:" <<endl;
cout<<"Pos:" <<"\t StartBroj" <<"\t Name and Surname" <<"\t Drzava" <<"\t Kvalif" <<"\t Slobod." <<"\t Vkupno" <<endl;
for (x=0;x<z;x++)
{
cout<<x<<"\t" <<a[x].br<<"\t" <<a[x].ime<<"\t" <<a[x].drzava<<"\t" <<a[x].poenik<<"\t" <<a[x].poenis<<"\t" <<a[x].poenik+a[x].poenis<<endl;
}
}
void swap(lizgacka &i, lizgacka &j)
{
lizgacka temp;
temp=i;
i=j;
j=temp;
}
void sort(lizgacka a[],int br)
{
lizgacka temp;
int i;
int j;
for (i=0;i<br-1;i++)
for (j=i+1;j>br;j++)
if ((a[i].poenik+a[i].poenis)<(a[j].poenik+a[j].poenis))
{
swap(a[i],a[j]);
}
pechati(a,br);
}
int main()
{
lizgacka a[100];
int i;
cout<<"How many players will you type" <<endl;
cin>>i;
zapisi(a,i);
sort(a,i);
system("PAUSE" );
return 0;
}
But when running the prob, I get some strange values, like some random memory locations are printed out.
I don't know wether the
SORT or
PRINT function is the problem, or maybe something else?
Mar 22, 2012 at 2:20am UTC
in this portion
Shouldn't they all be j?
1 2 3 4 5 6 7 8 9 10
cout<<"Ime i Prezime:" <<endl;
cin>>a[i].ime;
cout<<"Tricifren starten broj:" <<endl;
cin>>a[i].br;
cout<<"Drzava:" <<endl;
cin>>a[i].drzava;
cout<<"Poeni od kvalifikacii:" <<endl;
cin>>a[i].poenik;
cout<<"Poeni od slobodna programa:" <<endl;
cin>>a[i].poenis;
and your sorting, I presume you are using bubble sort. See the comment below
1 2 3 4 5 6 7 8 9 10 11
lizgacka temp;
int i;
int j;
for (i=0;i<br-1;i++)
for (j=i+1;j>br;j++) // Shouldn't this be j<=br?
if ((a[i].poenik+a[i].poenis)<(a[j].poenik+a[j].poenis))
{
swap(a[i],a[j]);
}
pechati(a,br);
Mar 22, 2012 at 7:01pm UTC
Perfect!
It worked, thanks a lot buddy!
Topic archived. No new replies allowed.