2014-02-04 5 views
0

Итак, я очень к этому отношусь, и я пытаюсь создать программу, которая будет вычислять стоимость любого количества междугородних звонков. Я еще не очень далеко, я застрял, пытаясь понять, как заставить функцию повториться. Прямо сейчас я получаю сообщение об ошибкеСоздание функции цикла для вычисления стоимости

Строка 18 здесь не допускается определение функции перед '{' токеном и ожидаемым ',' или ';' перед '{' токеном.

Линия 18 является линией непосредственно послеvoid costCalc(int numCalls)

Вот мой код до сих пор:

#include<iostream> 
using namespace std; 

int main() 
{ 
    // Declare and initialize all variables 
     int numCalls = 0; 
     int length = 0; 
     int hour = 0; 
     char day = ' '; 
     char dest = ' '; 
     double cost = 0.0; 

     cout<<"Enter the number of calls: "; 
     cin>>numCalls; 

     void costCalc(int numCalls) 
{ 
     if (numCalls > 0) 
     { 
      cout<<"Enter length of call in minutes: "; 
      cin>>length; 
      costCalc(numCalls-1); 
     } 
} 

    // Request the number of calls from the user 

    // Loop for the requested number of calls: 

// Request the user to give you the call length, 
// call day of week and hour of call, and call 
// destination 

// Instantiate and initialize a Call object 
// using either 
// a) the 4-parameter constructor, OR 
// b) the default constructor and each of the 
//  set member functions. 

// Get the cost of the call using the calcCallCost 
// function and add it to the total cost of the calls. 

// Use the callMsg function to print a message about the call 

    // end loop 

// Report the total cost of all the calls. 

    system("pause"); 
    return 0; 
} 
+4

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

+1

C не разрешает вложенные функции, как указано в @WilliamCustode - переместить вашу функцию 'costCalc()' до значения выше 'main()'. – twalberg

+0

Действительно ли это 'C'? Я не видел 'using namespace std;' ни 'cin', ни' cout' внутри какого-либо источника 'C' ... (исправьте меня, если я ошибаюсь. Я тоже' C') – core1024

ответ

0

Вы должны закрыть основную функцию перед началом нового.

Вы пытаетесь создать вложенную функцию внутри main и C или C++ не поддерживают это.

Вы должны просто скопировать/вставить код функции costCalc перед началом основной функции.

В качестве побочного примечания, давным-давно (1994), gcc (2.95.2) поддерживает вложенные функции как расширение. Но он никогда не приходил в стандарт C или C++.

Я не совсем уверен, почему вложенные функции никогда не попадали в стандарт. Он достаточно прост для поддержки (мы, вероятно, должны были бы сделать вложенную функцию встроенной статикой, но тем не менее). Возможно, потому что это вызовет проблемы с компоновщиком и компиляцией.

Это не большая проблема, и большинство случаев использования можно разрешить с помощью пространств имен.

0

Это поможет вам отправиться на шоу.

#include <iostream> 
    #include <iomanip> // for setprecision(2) 
    using namespace std; 

    class Call { 

    private: double length; 

    public: 
     // Instantiate and initialize a Call object 
     // using either 
     // a) the 4-parameter constructor, OR 
     Call(double theLength) 
     { 
      this->length = theLength; 
     } 

     // b) the default constructor and each of the 
     //  set member functions. 
     Call() { } 

     void SetLength(double someLength) 
     { 
      this->length = someLength; 
     } 

     double GetLength() 
     { 
      return this->length; 
     } 
    }; 

    double costCalc(double costPerMinute, int length) 
    { 
     Call thisCall(length); 
     return thisCall.GetLength()*costPerMinute; 
    } 

    void callMsg() 
    { 
     cout << "This is a message about the call" << endl; 
    } 

    int main() 
    { 
     int numCalls = 0; 
     int length = 0; 
     double cost = 0.0; 
     double costPerMinute = 0.05; 

     // Request the number of calls from the user 
     cout << "Enter the number of calls: "; 
     cin >> numCalls; 

     // Loop for the requested number of calls: 
     for (int i = 0; i < numCalls; i++) 
     { 
      // Request the user to give you the call length,   
      cout << "Enter length of call " << i << " in minutes: "; 
      cin >> length; 

      // Get the cost of the call using the calcCallCost 
      // function and add it to the total cost of the calls. 
      cost += costCalc(costPerMinute, length); 


      // Use the callMsg function to print a message about the call 
      callMsg(); 

     } // end loop 


     // Report the total cost of all the calls. 
     cout << "Total cost is $" << setprecision(2) << cost << endl; 

     return 0; 
    } 

Compile/пробег:

g++ cost.cpp 
$ ./a.out 
Enter the number of calls: 2 
Enter length of call 0 in minutes: 1 
This is a message about the call 
Enter length of call 1 in minutes: 2 
This is a message about the call 
Total cost is $0.15 
+0

Ваша реализация costCalc - это утечка памяти ... –

+0

Будет обновляться. Одиночный вызов free() будет исправлен. – slater

+0

Вы, вероятно, имеете в виду 'delete'. Но стоит ли вообще использовать динамическое распределение? Или даже класс? –

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