2011-05-03 2 views
-1

나는 프로그램에 설명을 적어 놓았습니다. 그러나 나는이 프로그램에 대해서 하나의 문제만을 가지고있다. 나는 많은 양의 데이터로 테스트했다. 내 프로그램의 유일한 문제는 내 displayContent 함수가 컴퓨터가 아니라는 것입니다. 프로그램은 내가 검색하고 싶은 사람의 이름을 입력 할 때까지 작동합니다. 내가 입력 할 때, 프로그램이 계속 진행될 때 종료되고 내 displayContent 함수에서 정보를 출력합니다. 함수에서 이진 검색에 문제가있을 수 있다고 생각합니다. 그러나 나의 실수가 어디에 있는지 확실하지 않다. 프로그램 오류가 발생하지 않습니다. 이 때.내 이진 검색에 문제가 있습니다.

cin>>search; 
if(search=='Y' || 'y') 
{ 
    cout<<"Please enter the name of the person which you would like to search. "; 
    getline(cin, name); 
    cin.ignore(); 
    displayContent(contestant, count, name); 
} 

내가 CIN은 >>을의 getline은 그것의 발견하게됩니다 버퍼에 수익을 남길 것이라고 믿는다 :

/* M. Elliot Frost 
CMPSC 121 Sect 901 
This program mimics the scores for a "Star Search" or other competion where 
5 judges give a contestant a score, the score is totaled after dropping the 
maximum and minimum score. The program will employ 4 functions: one to get 
the score from a specific judge for a specific contestant (this will be called 
once for each judge), one the calculates the average score after dropping the  highest 
and lowest scores, one that determines the maximum judges score for a specific 
contestant, and one that determines the mnimum score for a specific contestant. 

input: contestant's name, 5 Judges' names, 5 judges' scores 
ouput: contestant's name, scores from the five judges, and final score 
processing: enter the contestant name, enter the five judges' names, call a 
function multiple times to input a judge's score for specific contestant, 
call a function to calculate the final score. 
test data:/*contestant names = Shayna Skahan, Kelsey Himes, Kyle Strotz, David Cycon, Kristin Karg, Brad Lefever, Christy Collins, John Leonard, Puppy Chow 
scores for shayna=1,2,3,4,5 
scoreforkelsey=1.2,2.2,3.2,4.2,5.2 
scoreforKyle=9,8,7,6,5 
scoreforDavid=4.5,3.4,2.3,1.2,5.1 
scoreforKristin=1.234,2.345,3.456,4.567,5.678 
scoreforBrad=1,3,5,7,9 
scoreforChrist=2,4,6,8,1.1 
scoreforJohnLeonard=3,3.4,5,5.6,7.85 
scoreforPuppyChow=1.45,2.45,3.45,4.45,5.45 
judge names (respective to scores)=1)Ryan Nolt 2)Griff Galante 3)Brett Graeff 4)Dan Lee 5)Elliot Frost 


*/ 

#include <iostream> 
#include <string> 
#include <cctype> 
#include <iomanip> 
using namespace std; 



struct info 
{ 
string name; 
double score[5]; 
double avg; 
}; 
//function prototypes 
void getJudgeData(double& , string , string); 
double calcScore(double, double, double, double, double); 
double findLowest(double, double, double, double, double); 
double findHighest(double, double, double, double, double); 
void printScores(info[], int); 
void sortAscenduno(info[], int); 
void sortAscenddue(info[], int); 
void sortDescenduno(info[], int); 
void sortDescenddue(info[], int); 
void displayContent(info[], int, string); 
int main() 
{ 

info contestant[25]; 
string judge[5]; 
char again = 'y'; 
char sort, sortby, howsort, search; 
int count=0; 
string name; 

//Loop control structure (for loop to enter judges names) 
for (int i = 0; i < 5; i++) 
{ 
    cout<<"Please enter the "<< i + 1 <<" judge's first and last name. "; 
    getline(cin,judge[i]); 
}//end loop to enter judges names 


//loop control structure(for loop to enter contestants names and scores) 
while(count<25 && again =='y') 
{ 
    cout<<"\nPlease enter the contestant's first and last name. "; 
    getline(cin,contestant[count].name); 


    cout<<endl; 

    //Loop control structure(used for loop to call function(s) 5 times) 
    for(int j=0;j<5;j++) 
    { 
      getJudgeData(contestant[count].score[j], contestant[count].name, judge[j]); 
    } 

     //call function to calculate average 
     contestant[count].avg = calcScore(contestant[count].score[0], contestant[count].score[1], contestant[count].score[2],contestant[count].score[3], contestant[count].score[4]); 

    //output current contestant's scores 
     cout<<"\n\nThe scores for contestant "<<contestant[count].name<<" were \n" 
      <<contestant[count].score[0]<<" from "<<judge[0]<<endl<<contestant[count].score[1]<<" from " 
    <<judge[1]<<endl<<contestant[count].score[2]<<" from "<<judge[2]<<endl<<contestant[count].score[3] 
    <<" from "<<judge[3]<<" and "<<endl<<contestant[count].score[4]<<" from " 
    <<judge[4]<<endl<<"\nThe average was "<<setprecision(1)<<fixed<<contestant[count].avg<<endl; 


    cout<<"\n\nIs there another contestant (y/n)? "; 
    cin>>again; 
    cin.ignore(); //removes newline from input stream 
    cout<<endl; //just to some space between contestants 

    count+=1;//compound assignment operator 
}// end of loop to enter contestants names and scores 

cout<<"There were "<<count<<" contestants in this round."<<endl; 


//call function to print all scores 
printScores(contestant, count); 



cout<<"Would you like to sort these scores? "; 
cin >>sort; 
sort = toupper(sort);//to give back an uppercase letter so the user can enter a lower or upper case 

while (sort == 'Y') 
{ 

    cout<<"Please enter a: \n\tN to sort by names of the contesants or \n\tS to sort by the average scores"<<endl; 
    cin>>sortby; 
    sortby = toupper(sortby); 
    //While loop to check validity of sortby variable 
    while(sortby != 'N' && sortby != 'S') 
    { 
     cout<<"You entered an invalid choice"<<endl; 
     cout<<"Please enter a: \n\tN to sort by names of the contesants \n\tS to sort by the average scores \n\t or C to display the information of a single contestant."<<endl; 
     cin>>sortby; 
     sortby = toupper(sortby);//sends upper case letter to sort by 
    }//end check of sortby loop 

    switch(sortby)//switch for score to sort by 
    { 
     case 'N': do //sorting contestants by name 
        { 
         cout<<"Would you like to sort ascending (a) or descending (d) \nby the contestants' names? "; 
         cin>>howsort; 
          howsort = tolower(howsort);//to give back an lowercase letter so the user can enter a lower or upper case 
        }while (howsort != 'a' && howsort != 'd'); // end howsort loop 

        if (howsort == 'a') 
        { 
         sortAscenduno(contestant, count); 
         cout<<"\nAfter sorting ascending according to contestants' names"<<endl;//callfunction to sort by ascending name 
         printScores(contestant, count);//call function to print structure array 
        }//end if 
        else 
        { 
         sortDescenduno(contestant, count);//callfunction to sort by descending name 
         cout<<"\nAfter sorting descending according to contestants' names"<<endl; 
         printScores(contestant, count);//call function to print structure array 
        }//end else 
        cout<<"Would you like to search for a single contestant?"; 
        cin>>search; 
        if(search=='Y' || 'y') 
        { 
         cout<<"Please enter the name of the person which you would like to search. "; 
         getline(cin, name); 
         cin.ignore(); 
         displayContent(contestant, count, name); 
        } 
        break;//not to exit a loop but the switch 

     case 'S': do 
         {//sorting by avg score from contestants       { 
          cout<<"Would you like to sort ascending (a) or descending (d) \nby the contestants' average scores? "; 
          cin>>howsort; 
          howsort = tolower(howsort); 
         }while (howsort != 'a' && howsort != 'd'); // end howsort loop 

         if (howsort == 'a')//if loop to sort ascending to average score 
         { 
          sortAscenddue(contestant, count); 
          cout<<"\nAfter sorting ascending according to contestants' average score"<<endl; 
          printScores(contestant, count); 
         }//end if 
         else 
         { 
          sortDescenddue(contestant, count); 
          cout<<"\nAfter sorting descending according to contestants' average score"<<endl; 
          printScores(contestant, count); 
         }//end else 
         cout<<"Would you like to search for a single contestant?"; 
         cin>>search; 
         if(search=='Y' || 'y') 
         { 
          cout<<"Please enter the name of the person which you would like to search. "; 
          getline(cin, name); 
          cin.ignore(); 
          displayContent(contestant, count, name); 
         } 
         break;//not to exit a loop but to exit the switch 



    }//end switch 

     cout<<"Would you like to sort these scores again? "; 
     cin >>sort; 
     sort = toupper(sort); 
} 

return 0; 
} 

/*function to enter a single judge's score for a contestant. 
input: score as a reference parameter, contestant name and judge's name as 
    value parameters. 
output: the score will be passed back to the function call by the reference 
     parameter. 
processing: ask for the score and validate that it is between 0 and 10 using 
      a while loop. 
Pre: Contestant's and Judges' names have been entered. 
Post: score for a specific contestant by a specific judge will be sent back 
    to call. 

*/ 
void getJudgeData(double& value, string contname, string judname) 
{ 
cout<<"Please enter the score for "<<contname<<" from "<<judname<<". "; 
cin>>value; 
//to validate the score and asks the user to reenter 
while (value < 0 || value > 10) 
{ 
    cout<<"An invalid score was entered. \nPlease enter the score for " 
     <<contname<<" from "<<judname<<" again. "; 
    cin>>value; 
} 
} 

/*Function to calculate the average score after eliminating the 
the highest and lowest scores. 
input: five scores, passed by value 
output: average will be displyed to screen 
processing: add five scores together 
      call function to determine highest score and subtract that. 
      call function to lowest score and subtract 
      divide by 3 (because there were 5 scores but minus the lowest and highest 
      there are only three doubles at this point) 

Pre: five valid scores have been determined 
Post: Average will be output to the screen 
*/ 
double calcScore(double sc1, double sc2, double sc3, double sc4, double sc5) 
{ 
double small, big, mean; 

//call function to find lowest 
small = findLowest(sc1, sc2, sc3, sc4, sc5); 

//call function to find highest 
big = findHighest(sc1, sc2, sc3, sc4, sc5); 

mean = (sc1 + sc2 + sc3+ sc4 + sc5 - small - big)/3; 

cout<<"\nThe average score was "<<setprecision(1)<<fixed<<mean<<endl; 
return mean; 
} 

/*function to determine the lowest value of the 5 scores 
input: five scores passes by value 
output: the lowest score will be sent back to call by a return 
     statement 
processing: low to the first score initially. Then use a 
      series of ifs to compare low to other scores 
Pre: That five valid scores have been enterd 
Post: The lowest socre is returned to function call 
*/ 

double findLowest(double one, double two, double three, double four, double five) 
{ 
double low; 
low = one; 
//compare to second score 
if (two < low) 
{ 
    low = two; 
} 

//compare to third score 
if (three < low) 
{ 
    low = three; 
} 

//compare to fourth score 
if (four < low) 
{ 
    low = four; 
} 

//compare to fifth score 
if (five < low) 
{ 
    low = five; 
} 

cout<<"\nThe lowest of the five scores was "<<low<<endl; //for testing 
return low; 
} 


/*function to determine the highest value of the 5 scores 
input: five scores passes by value 
output: the highest score will be sent back to call by a return 
     statement 
processing: high to the first score initially. Then use a 
      series of ifs to compare low to other scores 
Pre: That five valid scores have been enterd 
Post: The highest socre is returned to function call 
*/ 

double findHighest(double one, double two, double three, double four, double five) 
{ 
double high; 
high = one; 
//compare to second score 
if (two > high) 
{ 
    high = two; 
} 

//compare to third score 
if (three > high) 
{ 
    high = two; 
} 

//compare to fourth score 
if (four > high) 
{ 
    high = four; 
} 

//compare to fifth score 
if (five > high) 
{ 
    high = five; 
} 

cout<<"\nThe highest of the five scores was "<<high<<endl; //for testing 
return high; 
} 

/*function to output all the scores for all the contestants for this round. 
input: taken from the main function is an array of structure data type 
and the number of contestants 
output: a title line containing judges names, then series of contestants names and  score 
Pre: Contestants names and scores have been entered, average score has been calculated 
Post: A table appears to screen 

*/ 
void printScores(info player[], int mag) 
{ 
cout<<"The scores for the contestants are \n  Contestant  Judge1 Judge2 Judge3 Judge4 Judge5 Average" 
     <<"\n______________________________________________________________________"<<endl; 

//loop to output contest name and scores 
for(int q = 0; q < mag; q++) 
{ 
    cout<<right<<setw(15)<<fixed<<setprecision(1)<<player[q].name<<setw(10)<<player[q].score[0]<<setw(8)<<player[q].score[1]<<setw(8)<<player[q].score[2]<<setw(8)<<player[q].score[3] 
     <<setw(8)<<player[q].score[4]<<setw(8)<<player[q].avg<<endl; 
} 
} 

/*function to sort arrays ascending in average score 
input: array of structure data type, and number of contestants 
output: no output generated, but array of structure data type 
will be sorted by ascending alphatbetically 
Processing: The bubble sort algorithm will be used 
Pre: scores will be entered and averages calculated 
Post: structure array will be rearranged 
*/ 
void sortAscenduno(info contender[], int n) 
{ 
int last = n-2, i; 
bool sawt = false; 
info temp; 


while (!sawt) 
{ 
    i = 0; 
    sawt = true; 

    while (i <= last) 
    { 
     int compare=contender[i].name.compare(contender[i+1].name); 
     if (compare > 0) 
     { 
      temp=contender[i]; 
      contender[i]=contender[i+1]; 
      contender[i+1]=temp; 

      sawt = false; 
     } 
     i++; 
    } 
    last = last -1; 
} 
} 

/*function to sort arrays descending by name 
input: array of structure data type, and number of contestants 
output: no output generated, but array of structure data type 
will be sorted by ascending alphatbetically 
Processing: The insertion sort algorithm will be used 
Pre: scores will be entered and averages calculated 
Post: structure array will be rearranged 
*/ 
void sortAscenddue(info participators[], int mult) 
{ 
int last=mult-2, i; 
int marker; 
bool sorted=true; 
// Insertion sort 
for (i = 0; i<= last; i++) 
{ 
    if (participators[i].avg > participators[i + 1].avg) 
    { 
     sorted = false; 
     marker = i; 
     info temp; 
     while (!sorted) // loop to place element in preceding list 
     { 
      temp = participators[marker];    //swapping elements of array 
      participators[marker] = participators[marker + 1]; 
      participators[marker + 1] = temp; 

      if (marker == 0) //at beginning of array 
      { 
       sorted = true; 
      } 
      else if (participators[marker].avg > participators[marker - 1].avg) //Check to see if in order 
      { 
       sorted = true; 
      } 
      else 
      { 
       marker = marker - 1;   //reset marker 
      } 

      cout<<endl; 


     } 
    } 
} 
} 
/*function to sort arrays descending to contestants' names 
    input: array of structure data type, number of contestants 
    output: Arrays will be changed with relationship of indices maintained 
Processing: The selection sort algorithm will be used 
Pre: scores will be entered and averages calculated 
Post: arrays will be rearranged 
*/ 
void sortDescenduno(info attend[], int numb) 
{ 
int outer, inner, maxi; 
info temp; 
int cmp; 
//nested loops for selection sort 
for(outer = 0; outer <numb-1; outer++) 
{ 
    maxi = outer; 
    for(inner = outer+1; inner < numb; inner ++) 
    { 
     cmp=attend[outer].name.compare(attend[inner].name); 
     if(cmp<0) 
     maxi = inner; 
    } 

    if (maxi != outer) 
    { 
     temp=attend[outer]; 
     attend[outer]=attend[maxi]; 
     attend[maxi]=temp; 
    } 
} 
} 


/*function to sort arrays descending to contestants' average scores 
    input: array of structure data type, number of contestants 
output: Arrays will be changed with relationship of indices maintained 
Processing: The selection sort algorithm will be used 
Pre: scores will be entered and averages calculated 
Post: arrays will be rearranged 
*/ 

void sortDescenddue(info people[], int amount) 
{ 
int second, first, larger; 
info temp; 
//nested loop for selection sort 
for(second = 0; second <amount-1; second++) 
{ 
    larger = second; 
    for(first = second+1; first < amount; first ++) 
    { 
     if(people[second].avg < people[first].avg) 
     larger = first; 
    } 

    if (larger != second) 
    { 
     temp=people[second]; 
     people[second]=people[larger]; 
     people[larger]=temp; 
    } 
} 
} 

/*Function will be able to let user search for any contestant and will print all of  their information 
input:taken from main is the array of structure data type, the number of contestants, and a string variable 
output:printed is one contestant from the structure data type 
processing: binary search is done 
pre:elements of the structure data type array are entered 
post: one elements will be output to the screen 

*/ 
void displayContent(info contest[], int quantity, string id) 
{ 
int first=0, 
    last=quantity-1, 
    middle, 
    position=-1; 
bool found=false; 

while(first<=last && !found) 
{ 

    middle=(first+last)/2; 
    int look=contest[middle].name.compare(id); 
    if(look==0) 
    { 
     found=true; 
     position=middle; 
    } 
    else if(look>0) 
    { 
     last=middle-1; 
    } 
    else 
    { 
     first=middle+1; 
    } 
} 
if(position==-1) 
    { 
     cout<<"That person was not one of the contestants."; 
    } 
    else 
    { 
     cout<<"The scores for "<<id<<" are \n  Contestant  Judge1 Judge2 Judge3 Judge4 Judge5 Average" 
       <<"\n______________________________________________________________________"<<endl; 
     cout<<right<<setw(15)<<fixed<<setprecision(1) <<contest[position].name<<setw(10)<<contest[position].score[0]<<setw(8) <<contest[position].score[1]<<setw(8)<<contest[position].score[2]<<setw(8) <<contest[position].score[3] 
     <<setw(8)<<contest[position].score[4]<<setw(8) <<contest[position].avg<<endl; 
    } 
} 
+9

모든면에서 우리는 귀하의 모든 코드를 읽고 싶지는 않습니다. 스 니펫 (snippets)을 선택하고 멋진 최소한의 예제를 게시하고 디버그하고 이것이 깨지는 곳을 확인하십시오. 또한 'cout <<'스팸 메일은 내가 본 중에 가장 끔찍한 일 중 하나입니다. – Lacrymology

+0

+1000과 Lacrymology –

+0

나는이 웹 사이트가 나 자신과 같은 초보 프로그래머의 질을 떨어 뜨리기위한 것이라는 것을 몰랐다. 누군가에게 불편을 끼쳐 드려 죄송합니다. –

답변

1

모든 코드를 보지 않고이 세그먼트를보고 할 수 있습니다 텍스트를 입력하기 전에 종료 조건을 설정하십시오 (설명 된 문제와 비슷합니다).

(당신이 언급 한 cout으로 디버깅 포인트를 넣고 거기에서 디버그 해보십시오.) 문제를 발견하는 것을 멀리하고 싶지 않습니다. 내가 설명한 것이 문제 일 경우 간단한 해결책이 있습니다. .)

관련 문제