Значение, напечатанное в одной функции, работает нормально, но напечатано в следующей функции неправильно (возвращает 0,00) - PullRequest
1 голос
/ 21 сентября 2011

Я очень новичок в этом, поэтому, пожалуйста, потерпите меня. Для кодирующего класса C мы должны использовать всего девять функций и файл заголовка (мы называем его my.h), чтобы собрать длину и ширину комнаты (в дюймах), процентную скидку (также int ), и цена за единицу ковра (двойной). Мы используем входные данные для расчета общей стоимости установки ковра. Я могу получить длину, ширину и площадь для печати, но не цену за единицу. Он печатает frin из функций Read_Data.c и Calc_Value.c, но не из Install_Price.c, который вызывается в Calc_Value.c. unit_price читается в то же время, что и длина и ширина, но, так или иначе, она не прошла правильно. Я не уверен почему. Может быть, это требует другого указателя. Любая помощь будет очень цениться. Я прочитал свою книгу и поговорил с моим профессором и одноклассниками, а также искал в Интернете, но я не нашел ничего, что могло бы помочь. Код для Install_Price:

/*This function calculates the cost of the carpet and the labor cost in order to    
calculate the installed price.*/

#include "my.h"

void Install_Price (int length, int width, int unit_price, int* area, 
double* carpet_cost, double* labor_cost, double* installed_price)

{

printf("\nThe unit price is %7.2f.\n", *unit_price);

*area = length * width;
*carpet_cost = (*area) * unit_price;

printf("The carpet cost is %7d x %7.2f = %7.2f.\n", *area, unit_price, *carpet_cost);

*labor_cost = (*area) * LABOR_RATE;
*installed_price = (*carpet_cost) + (*labor_cost);

return;
}

Обратите внимание, что операторы printf здесь просто для того, чтобы попытаться выяснить, где я ошибся с unit_price. Ниже я включил код заголовка my.h, main.c и функции, которые он вызывает, до Install_Price.c. Еще раз спасибо за вашу помощь!

my.h

#include <stdio.h>
void Read_Data(int* length, int* width, int* percent_discount, double* 
unit_price);

void Calc_Values(int length, int width, int percent_discount, double 
unit_price, int* area, double* carpet_cost, double* labor_cost, double* 
installed_price, double* discount, double* subtotal, double* tax, 
double* total);

void Install_Price(int length, int width, int unit_price, int* area, double*      
carpet_cost, double* labor_cost, 
double* installed_price);

void Subtotal (int percent_discount, double installed_price, double* discount, 
double* subtotal);

void Total (double subtotal, double* tax, double* total);

void Print (int length, int width, int area, double unit_price, double carpet_cost,    
double labor_cost, double 
installed_price, int percent_discount, double discount, double subtotal, double tax,   
double total);

void Print_Measurements (int length, int width, int area);

void Print_Charges (double unit_price, double carpet_cost, double labor_cost, double   
installed_price, int percent_discount, double discount, double subtotal, double tax, 
double total);

#define LABOR_RATE 0.35
#define TAX_RATE 0.085

main.c

/*  This function calls three subfuctions to calculate the costs of installing a    
carpet and prints an invoice.  */

#include "my.h"

int main (void)

{
        int length;
        int width;
        int percent_discount;
        double unit_price;
        int area;
        double carpet_cost;
        double labor_cost;
        double installed_price;
        double discount;
        double subtotal;
        double tax;
        double total;

Read_Data(&length, &width, &percent_discount, &unit_price);

Calc_Values(length, width, percent_discount, unit_price, &area, &carpet_cost,  
&labor_cost,&installed_price, &discount, &subtotal, &tax, &total);

Print(length, width, area, unit_price, carpet_cost, labor_cost,
installed_price, percent_discount, discount, subtotal, tax, total);

return 0;
}

Read_Data.c

/*This function asks the user for the length and width of a room to be carpeted, the  
percent discount and the unit price of the carpet. */

#include "my.h"

void Read_Data (int* length, int* width, int* percent_discount, double* unit_price)

{
printf("What is the length, in feet, of the room?\n");
scanf("%d", length);

printf("What is the width, in feet, of the room?\n"); 
scanf("%d", width);

printf("What is the percent discount?\n");
scanf("%d", percent_discount);

printf("What is the unit price of the carpet?\n");
scanf("%lf", unit_price);

printf("\nThe length is %6d.\n", *length);   //These printf statements work properly.
printf("The width is %6d.\n", *width);
printf("The percent discount is %3d%.\n", *percent_discount);
printf("The unit price is $%7.2f.\n", *unit_price);

return;
}

Calc_Value.c

/*This function calls three subfuctions that calculate all required quantities.  */

#include "my.h"

void Calc_Values (int length, int width, int percent_discount, double unit_price, 
int* area, double* carpet_cost, double* labor_cost, double* installed_price, double*  
discount, double* subtotal, double* tax, double* total)

{

printf("\nUnit Price:  %7.2f.\n", unit_price);  //This printf statement works properly.

Install_Price (length, width, unit_price, area, carpet_cost, labor_cost, 
installed_price);

Subtotal (percent_discount, *installed_price, discount, subtotal);

Total (*subtotal, tax, total);

return;
}

Install_Price.c (повторяется для удобства пользователя)

/*This function calculates the cost of the carpet and the labor cost in order to    
calculate the installed price.*/

#include "my.h"

void Install_Price (int length, int width, int unit_price, int* area, 
double* carpet_cost, double* labor_cost, double* installed_price)

{

printf("\nThe unit price is %7.2f.\n", *unit_price);  //THIS DOES NOT WORK

*area = length * width;
*carpet_cost = (*area) * unit_price;

printf("The carpet cost is %7d x %7.2f = %7.2f.\n", *area, unit_price, 
*carpet_cost);  //THIS DOES NOT WORK

*labor_cost = (*area) * LABOR_RATE;
*installed_price = (*carpet_cost) + (*labor_cost);

return;
}

Ответы [ 2 ]

8 голосов
/ 21 сентября 2011

Я не прочитал весь вопрос, но я уже заметил здесь ошибку:

printf("\nThe unit price is %7.2f.\n", *unit_price);

и

printf("The carpet cost is %7d x %7.2f = %7.2f.\n", *area, unit_price, *carpet_cost);

Переменная unit_price имеет тип int, но вы печатаете его как плавающую точку.

Я предполагаю, что первое утверждение вообще не должно даже компилироваться, поскольку unit_price даже не может быть разыменовано.

2 голосов
/ 21 сентября 2011

Ваша проблема в том, что в объявлении функции Install_Price unit_price объявлен int, но во всех других определениях функций он объявлен double или *double.C автоматически приводит double к int, когда вы передаете это значение Install_Price.Проблема связана с этими двумя строками кода в Install_price:

printf("\nThe unit price is %7.2f.\n", *unit_price);

и

printf("The carpet cost is %7d x %7.2f = %7.2f.\n", *area, 
       unit_price, *carpet_cost);

. Вы используете %f, чтобы напечатать цену за единицу, которая была приведена кint.

Изменение определения Install_Price на

void Install_Price (int length, int width, double unit_price, int* area, 
double* carpet_cost, double* labor_cost, double* installed_price)

Должно решить одну из ваших проблем.

Другая проблема также в этой строке:

printf("\nThe unit price is %7.2f.\n", *unit_price);

unit_price не должна быть разыменована в этой строке.Измените это на:

printf("\nThe unit price is %7.2f.\n", unit_price);

Чтобы исправить эту проблему.

...