Создание функции цикла для расчета стоимости

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

Строка 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;
}

person user2040308    schedule 04.02.2014    source источник
comment
У вас есть функция, объявленная в функции. Переместите фигурные скобки. Кроме того, хорошее использование рекурсии для нового программиста.   -  person Will Custode    schedule 04.02.2014
comment
C не допускает вложенных функций, как указал @WilliamCustode - переместите свою функцию costCalc() выше main().   -  person twalberg    schedule 05.02.2014
comment
Это вообще C? Я не видел ни using namespace std;, ни cin, ни cout ни в одном C источнике... (поправьте меня, если я ошибаюсь. Я тоже C новичок)   -  person core1024    schedule 05.02.2014
comment
@ core1024, ты прав. Это не C; это C++. Потоки не поддерживаются в C.   -  person Stephen Rasku    schedule 05.02.2014


Ответы (2)


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

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

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

Кстати, давным-давно (1994) gcc (2.95.2) поддерживал вложенные функции как расширение. Но он так и не вошёл в стандарт C или C++.

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

На самом деле это не имеет большого значения, и большинство вариантов использования можно решить с помощью пространств имен.

person kriss    schedule 05.02.2014

Это заставит вас идти на шоу.

    #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;
    }

Скомпилировать/запустить:

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
person Community    schedule 05.02.2014
comment
Вероятно, вы имели в виду delete. Но нужно ли вообще использовать динамическое размещение? Или хотя бы класс? - person François Moisan; 05.02.2014
comment
Вопрос требует создания экземпляра класса (это напоминает домашнее задание...) и имеет риторическую цель для спрашивающего. - person ; 05.02.2014
comment
Я понимаю. Я пропустил эту часть. - person François Moisan; 05.02.2014
comment
Добавлено удаление(thisCall); - person ; 05.02.2014