2015-04-12 2 views
1

Я работаю над созданием программы для класса, где мы должны были отобрать список классов (до 100 классов), сортировать их и выводить среднюю и среднюю, а также список оценок с 5 классами в строке. У меня закончен код, он работает и запускается, но выходит без вывода. один шаг, чтобы найти ошибку, он попадает в точку, где он переходит к строке WPRFLAG в другом файле crtexe.c. Я хотел опубликовать свой код и посмотреть, сможет ли кто-нибудь помочь мне в правильном направлении. Прямо сейчас, я не знаю, что это за wprflag и не вижу, почему мой код просто выходит.C++ Broken Program - WPRFLAG?

#include <iostream> 
#include<string> 
#include<vector> 
#include<algorithm> 
#include<cmath> 
#include<iomanip> 
#include<sstream> 
using namespace std; 
inline void keep_window_open() { char ch; cin>>ch; } 
///////////////////////////////Function Prototypes/////////////////////////////// 
double mean (int[], int); 
double median (int[], int); 
///////////////////////////////Main////////////////////////////////////////////// 
//Main takes input for up to 100 grades and stores in an array then calls the 
//mean and median functions for those calculations then outputs the mean, median, 
//and list of grades sorted low to high with 5 grades per line 
//Main takes input in as a string and coverts to int. This is to allow user to 
//enter EXIT to end the input loop. There is some error checking built in so 
//use can only enter 0-100 or exit. 
int main() 
{ 
int counter=0, valueInt=0, numberGrades=0;      
//counter is used to limit loop to 100 cycles and indicate which element in 
//array to store valueInt 
int grades [100] = {0};     
string valueString=" "; 
cout<<"Use this program to calculate the Mean and Median of up to 100 "; 
cout<<"grades.\n**Please enter positive real whole numbers only "; 
cout<<"(0-100).\n"; 
do            //main input loop 
{ 
    cout<<"Key in a grade and press [Enter] or type EXIT to end list\n"; 
    cin>>valueString; 
     if (valueString=="exit"||valueString=="EXIT"||valueString=="Exit") 
     { 
      break; 
     } 
     else 
     { 
      stringstream convert(valueString); //converts String to Int 
      if (!(convert>>valueInt))   //for array 
      {         
       valueInt=0;      
      }         

      if (cin.fail())      //error checking for any 
      {         //text input that is not 
       cin.clear();     //"exit" 
       cin.ignore(1000,'\n');     
       cout<<"Incorrect input. Try again\n"; 
       break; 
      } 
      if (valueInt<0||valueInt>100)  //error checking for 
      {         //0>valueInt>100 
       cout<<"Grades can only be 0-100. Please try again.\n"; 
       break; 
      } 
      else 
      { 
       grades[counter]=valueInt;  //Actual input into array 
       numberGrades++; 
       counter++; 
      } 
     } 
} 
while (counter<100); 
cout<<"The average grade point is "<<mean(grades, numberGrades)<<".\n"; 
cout <<"The median grade point is "<<median(grades, numberGrades)<<".\n"; 

for (int outer=0;outer<numberGrades;outer++)   //sorting loop 
{ 
    for (int inner=0;inner<numberGrades-1;inner++) 
    { 
     if (grades[inner]>grades[inner+1]) 
     { 
      swap(grades[inner], grades[inner+1]); 
     } 
    } 
} 

counter=0; 
for (int i=0;i<counter;i++)        //print list loop 
{ 
    cout<<grades[counter]<<" "; 
    counter++; 
    if (i==4) 
    { 
     cout<<"\n"; 
    } 



       //The next two lines stop the Command Prompt window from 
       //closing until the user presses a key, including Enter. 
       cout << "\nPress enter twice to exit." << endl; 
                cin.ignore(2); 
} 
} 
///////////////////////////////Mean////////////////////////////////////////////// 
//Mean() finds the averge of the list of grades stored in the grades array and 
//returns that value to the cout statement in main(). 
double mean (int grades[], int numberGrades) 
{ 
double total=0.0; 
for (int counter=0;counter<numberGrades+1;counter++) 
{ 
    total+=grades[counter]; 
} 
total=total/numberGrades; 
return (total); 
} 

///////////////////////////////Median//////////////////////////////////////////// 
//Median() first sorts the values stored in the grades array then finds the 
//median value. If numberGrades is odd value, will show the middle value of the 
//sorted array list. If numberGrades is an even value, will display the average 
//of the two middle values in the sorted array list. 
double median (int grades[], int numberGrades)    
{ 
double total=0.0; 
for (int outer=0;outer<numberGrades;outer++)   //sorting loop 
{ 
    for (int inner=0;inner<numberGrades-1;inner++) 
    { 
     if (grades[inner]>grades[inner+1]) 
     { 
      swap(grades[inner], grades[inner+1]); 
     } 
    } 
} 

if (numberGrades%2==0) 
{ 
    total=((grades[numberGrades/2]+grades[numberGrades/2-1])/2); 
} 
else 
{ 
    total=grades[numberGrades/2]; 
} 
return (total); 

} 

Просто хотел сказать спасибо за любое время, поставленное в это. Все отзывы очень ценятся! Я попытаюсь обновить это, если найду ответ.

+0

Вы уверены, что это условие: 'counter

+0

Попробуйте перешагнуть, вместо того, чтобы войти в систему, особенно при использовании стандартных библиотечных функций. – vsoftco

+1

, не глядя на ваш код, я копирую и вставляю его в среду визуальной студии, и похоже, что все работает отлично. Любой конкретный вход для воспроизведения проблемы? –

ответ

0

Перемещено нижние линии из конечной петли в основной функции. Это позволит консоли оставаться открытым для отображения вывода.

Программа работает правильно, как указано в коде. Мой вывод был неправильным из-за логической ошибки.

//The next two lines stop the Command Prompt window from 
//closing until the user presses a key, including Enter. 
cout << "\nPress enter twice to exit." << endl; 
cin.ignore(2);