2013-04-17 3 views
-1

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

Вот код:

#include <iostream> 
#include <iomanip> 
#include <cmath> 
#include <fstream> 


using namespace std; 


void header(int lab_number, char lab_part) 
{ 
    cout << "Kevin Schultz\n"; 
    cout << "Lab" << lab_number << lab_part << endl << endl; 
} 


double length, width, height, x, weight, total = 0, shipping_cost, volume; 




int main() 
{ 
    double calculate(double length, double width, double height); 
    double volume; 
    double chargeAmount; 
    double charge(ifstream & inFile, ofstream & prt); 


    ifstream inFile; 
    ofstream prt("lab7new_out.txt"); 

    header(7, 'A'); 
    prt << "  S & S Global Services\n"; 
    prt << " Shipping Cost Analysis Report\n\n"; 
    prt << "Length Width Height Weight Shipping\n"; 
    prt << "        Cost\n\n"; 

    inFile.open("c:\\lab7\\pkg.txt"); 
     if (!inFile) 
     cout << "Error opening the file\n"; 

    inFile >> length; 
    inFile >> width; 
    inFile >> height; 
    inFile >> weight; 


    volume = calculate(length, width, height);  
    chargeAmount = charge(inFile, prt); 



    prt << "------------------------------------" << endl; 
    prt << "\nTotal cost: $" << total; 

    system("pause"); 
    return 0; 

} 

double calculate(double length, double width, double height) 
     { 
      double volume; 
      volume = length * width * height; 
      return volume; 
     } 

double charge(ifstream & inFile, ofstream & prt) 
     { 
      const double basic_charge = 12; 
      const double Vsurcharge = 5; 
      const double Dsurcharge = 4; 
      const double Wsurcharge = 2; 
      double netWeight = 0; 

      while (!inFile.eof()) 
      { 
       shipping_cost = basic_charge; 

       if (volume > 7) 
        shipping_cost += Vsurcharge; 
       if (length > 3 || width > 3 || height > 3) 
        shipping_cost += Dsurcharge; 
       if (weight > 50) 
       { 
        netWeight = weight - 50; 
        shipping_cost += netWeight * Wsurcharge; 
       } 
       total += shipping_cost; 
       prt << setw(4) << right << setprecision(1) << length << setw(6) << right << setprecision(1) << width << setw(6) << right << setprecision(1) << height << setw(8) << right; 
       prt << weight << setw(5) << right << setprecision(2) << fixed << "$" << shipping_cost << endl; 

       inFile >> length; 
       inFile >> width; 
       inFile >> height; 
       inFile >> weight; 
      } 
      return total; 
     } 

Любая помощь будет здорово!

+3

Вы фактически не называете 'calculate' вообще. –

+0

@sftrabbit Я попробовал добавить: volume = расчет (объем); перед chargeAmount, но он не будет компилироваться. –

+0

Ваш профессор прав: избавиться от глобальных переменных. Все они. Не продолжайте, пока вы их не удалите. – molbdnilo

ответ

2

Как сказал ваш профессор, пожалуйста, не используйте глобальные переменные. В вашем коде у вас разные переменные volume, и я сомневаюсь, что вы знаете, когда вы обращаетесь к какой из переменных. Давайте проверим ваш код:

double volume; // global variable, never written, read in function charge 

int main() { 
    ... 
    double volume; // local variable, only visible in function main, but never used 
    ... 
} 

double calculate(double length, double width, double height) { 
    double volume; // local variable, only visible in calculate 
    volume = ...; 
    return volume; 
} 

double charge(ifstream & inFile, ofstream & prt) { 
    ... 
    if(volume > 7) // no local variable volume defined, so using global variable volume 
    ... 
} 

Кроме того, вы объявляете функцию вычисления, но вы ее никогда не называете.

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

+0

Спасибо за помощь! –

0

попробуйте что-то вроде этого. Problemn является то, что вам нужно, чтобы объявить прототип функции перед вызовом, но если вы кладете основную функцию в нижней части .c файла вам не нужно decalre прототип функции, надеюсь, что это ясно

#include <iostream> 
#include <iomanip> 
#include <cmath> 
#include <fstream> 


using namespace std; 


void header(int lab_number, char lab_part) 
{ 
    cout << "Kevin Schultz\n"; 
    cout << "Lab" << lab_number << lab_part << endl << endl; 
} 


double length, width, height, x, weight, total = 0, shipping_cost, volume; 

double calculate(double length, double width, double height) 
{ 
    double volume; 
    volume = length * width * height; 
    return volume; 
} 

double charge(ifstream & inFile, ofstream & prt) 
{ 
      const double basic_charge = 12; 
      const double Vsurcharge = 5; 
      const double Dsurcharge = 4; 
      const double Wsurcharge = 2; 
      double netWeight = 0; 

      while (!inFile.eof()) 
      { 
       shipping_cost = basic_charge; 

       if (volume > 7) 
        shipping_cost += Vsurcharge; 
       if (length > 3 || width > 3 || height > 3) 
        shipping_cost += Dsurcharge; 
       if (weight > 50) 
       { 
        netWeight = weight - 50; 
        shipping_cost += netWeight * Wsurcharge; 
       } 
       total += shipping_cost; 
       prt << setw(4) << right << setprecision(1) << length << setw(6) << right << setprecision(1) << width << setw(6) << right << setprecision(1) << height << setw(8) << right; 
       prt << weight << setw(5) << right << setprecision(2) << fixed << "$" << shipping_cost << endl; 

       inFile >> length; 
       inFile >> width; 
       inFile >> height; 
       inFile >> weight; 
      } 
    return total; 
} 

int main() 
{ 

    double volume = calculate(length, width, height); 
    double chargeAmount; 


    ifstream inFile; 
    ofstream prt("lab7new_out.txt"); 

    header(7, 'A'); 
    prt << "  S & S Global Services\n"; 
    prt << " Shipping Cost Analysis Report\n\n"; 
    prt << "Length Width Height Weight Shipping\n"; 
    prt << "        Cost\n\n"; 

    inFile.open("c:\\lab7\\pkg.txt"); 
     if (!inFile) 
     cout << "Error opening the file\n"; 

    inFile >> length; 
    inFile >> width; 
    inFile >> height; 
    inFile >> weight; 

    chargeAmount = charge(inFile, prt); 


    prt << "------------------------------------" << endl; 
    prt << "\nTotal cost: $" << total; 

    system("pause"); 
    return 0; 

} 
+0

Уступка требует, чтобы я использовал прототипы. –

+0

поместите свой прототип после команды using следующим образом: 'void header (int lab_number, char lab_part); двойной расчет (двойная длина, двойная ширина, двойная высота); двойной заряд (ifstream & inFile, ofstream & prt); ' – Nagasaki

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