2015-07-15 2 views
-2

Моя программа игнорирует оператор switch. Когда я запускаю его, я ввожу свой ввод, и он просто переходит к умолчанию, в котором говорится «Недействительный ответ». Что бы я ни вводил, он идет по умолчанию, полностью игнорируя случаи оператора switch. Я проверил код, и он выглядит совершенно нормально.Почему моя программа игнорирует оператор switch?

#include <iostream> 
#include <cmath> 
#include <algorithm> 
#include <vector> 
#include <stdio.h> 

using namespace std; 


void ave(); 
void lar(); 
void sma(); 
void med(); 
void sorta(); 
void sortd(); 
int n; 
int n1; 
int n2; 
int n3; 
int n4; 
int n5; 
int n6; 
int n7; 
int n8; 
int n9; 
int n10; 
int list[10] = {n1, n2, n3, n4, n5, n6, n7, n8, n9, n10}; 
int av; 
int la; 
int sm; 
int me; 
int sa; 
int sd; 
bool wayToSort(int i, int j) { return i > j; }; 

int main() 
{ 

int c; 
char q; 

cout<< "Enter the first integer"; 
cin>> n1; 
cout<< "Enter the second integer"; 
cin>> n2; 
cout<< "Enter the third integer"; 
cin>> n3; 
cout<< "Enter the fourth integer"; 
cin>> n4; 
cout<< "Enter the fifth integer"; 
cin>> n5; 
cout<< "Enter the sixth integer"; 
cin>> n6; 
cout<< "Enter the seventh integer"; 
cin>> n7; 
cout<< "Enter the eighth integer"; 
cin>> n8; 
cout<< "Enter the ninth integer"; 
cin>> n9; 
cout<< "Enter the tenth integer"; 
cin>> n10; 

cout<< "1 - If you wish to find the average of the integers, press 1 \n"; 
cout<< "2 - If you wish to find the largest integer, press 2 \n"; 
cout<< "3 - If you wish to find the smallest integer, press 3 \n"; 
cout<< "4 - If you wish to find the median number, press 4 \n"; 
cout<< "5 - If you wish to sort the integers in ascending order, press 5 \n"; 
cout<< "6 - If you wish to sort the integers in descending order, press 6 \n"; 

//c = getchar(); 

cin>> c; 

switch (c) 
{ 
     case '1': 
     ave(); 
     break; 

     case '2': 
     lar(); 
     break; 

     case '3': 
     sma(); 
     break; 

     case '4': 
     med(); 
     break; 

     case '5': 
     sorta(); 
     break; 

     case '6': 
     sortd(); 
     break; 

    default: 
     cout<< "Invaid choice"; 

     return 0; 
} 

void ave(); 
{ 
av = (n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10) /10; 
cout<< "The average of the numbers is " << av << endl; 


} 


void lar(); 
{ 
la = n1; 
if (n2 > la) 
    la = n2; 
else if (n3 > la) 
    la = n3; 
else if (n4 > la) 
    la = n4; 
else if (n5 > la) 
    la = n5; 
else if (n6 > la) 
    la = n6; 
else if (n7 > la) 
    la = n7; 
else if (n8 > la) 
    la = n8; 
else if (n9 > la) 
    la = n9; 
else if (n10 > la) 
    la = n10; 

cout<< "The largest integer is " << la << endl; 


} 



void sma(); 
{ 
    sm = n1; 
    if (n2 < sm) 
     sm = n2; 
    else if (n3 < sm) 
     sm = n3; 
    else if (n4 < sm) 
     sm = n4; 
    else if (n5 < sm) 
     sm = n5; 
    else if (n6 < sm) 
     sm = n6; 
    else if (n7 < sm) 
     sm = n7; 
    else if (n8 < sm) 
     sm = n8; 
    else if (n9 < sm) 
     sm = n9; 
    else if (n10 < sm) 
     sm = n10; 




} 

void med(); 
{ 
    sort(list, list + 10); 

    for (size_t i = 0; i != 10; ++i) 
     me = 0.5 * (list[n/2] + list[n/2-1]); 



     } 


void sorta(); 
{ 
    sort(list, list + 10); 

    cout<< "The sorted array looks like this " << endl; 
    for (size_t i = 0; i != 10; ++i) 
     cout<< list[i] << " "; 



} 

void sortd(); 
{ 
    vector<int> intVec = { n1, n2, n3, n4, n5, n6, n7, n8, n9, n10}; 
    sort(intVec.begin(), intVec.end(), wayToSort); 

    for (int i : intVec) 
     cout<< i << " "; 




} 



cout<< "\n Quit (y/n)"; 
cin>> q; 
q = getchar(); 

}

+2

c - целое число. не используйте цитаты –

+0

... или не делайте 'c' a' char', а не 'int'. –

ответ

2

В вашем коде есть много рефакторинга и много ошибок. Исправление и рефакторинга

#include <iostream> 
#include <algorithm> 
#include <array> 
using namespace std; 

int main() { 
    array<int, 10> arr; 
    int c; 
    cout << "Enter all the elements\n"; 
    for (int & i : arr) cin >> i; 
    cout<< "1 - If you wish to find the average of the integers, press 1 \n"; 
    cout<< "2 - If you wish to find the largest integer, press 2 \n"; 
    cout<< "3 - If you wish to find the smallest integer, press 3 \n"; 
    cout<< "4 - If you wish to find the median number, press 4 \n"; 
    cout<< "5 - If you wish to sort the integers in ascending order, press 5 \n"; 
    cout<< "6 - If you wish to sort the integers in descending order, press 6 \n"; 
    cin >> c; 
    switch (c) { 
    case 1: 
     cout << "The average of the numbers is " << accumulate(arr.begin(), arr.end(), 0)/arr.size() << endl; 
     break; 
    case 2: 
     cout << "The largest integer is " << *max_element(arr.begin(), arr.end()) << endl; 
     break; 
    case 3: 
     cout << "The smallest integer is " << *min_element(arr.begin(), arr.end()) << endl; 
     break; 
    case 4: 
     nth_element(arr.begin(), arr.begin() + arr.size()/2, arr.end()); 
     cout << "The median number is " << arr[arr.size()/2] << endl; 
     break; 
    case 5: 
     sort(arr.begin(), arr.end()); 
     for (int i : arr) cout << i << " "; 
     cout << endl; 
     break; 
    case 6: 
     sort(arr.begin(), arr.end(), greater<int>()); 
     for (int i : arr) cout << i << " "; 
     cout << endl; 
     break; 
    default: 
     cerr << "Invaid choice\n"; 
     return 1; 
    } 
    return 0; 
} 

См LIVE VERSION.

+0

Мой компилятор не распознает

+0

В нем говорится: «bit/stdC++. h file not found» –

+0

Спасибо, потому что Xcode не имеет gcc и не может распознать Я использовал другие библиотеки, и он отлично работал. –

4

Вы на самом деле не вызов функции здесь:

case '1': 
    void ave(); 
    break; 

На самом деле вы просто объявить функцию.

Вместо этого она должна быть:

case '1': 
     ave(); // call function `ave()` 
     break; 

То же для всех остальных случаев в вашем switch.

Возможны и другие проблемы, но вы не показали нам MCVE, так что это сложно сказать.

+0

Я сначала попробовал его без пустоты, и он дал мне ошибки, говорящие «ave(), ссылающиеся на _main. –

+0

Как я уже говорил выше, могут быть и другие проблемы, но вы не показали нам [MCVE] (http: //stackoverflow.com/help/mcve). Пожалуйста, сделайте это, и тогда мы сможем помочь вам исправить любые другие проблемы. (FWIW это похоже на 'ave()' либо не определено/не реализовано, либо находится в другом исходном файле, а вы 're не связывая этот файл.) –

+2

@HamzahHashmi: Вы должны были объявить 'ave' перед коммутатором, и обычно вы объявляете его вне вызывающей функции (т.е. до main) – MSalters

Смежные вопросы