В настоящее время я нахожусь в классе C++ и изучаю функции. Наше задание состояло в том, чтобы создать программу для расчета общей стоимости, включая цену за кв. Фут, рабочую силу и налог в каждой комнате, заданную пользователем для подсчета. Вот моя программа, которую я не могу скомпилировать, и я не знаю почему. Спасибо всем, кто мне помогает, я очень благодарен.
Например, вход: 2 2 2 2 2 2 2
Должен дать результат: 2 2 22,4
но вместо этого он печатает это:
2 2 9,87
Я понятия не имею, что не так. Я посмотрел на все свои формулы, и они выглядят правильными. Комната с размерами 2 * 2, стоимость за кв. Фут 2, должна дать общую стоимость 11,2, я так смущен. Может быть, я неправильно установил функции?
#include <iostream>
#include <iomanip>
using namespace std;
void getdata (int&, int&, float&);
float InstalledPrice (int , int, float );
float totalprice (float);
void printdata (int , int, float);
int length, width, count, x;
float installation, costpersqfoot, price;
int main()
{
cout << "Enter the amount of rooms.\n";
cin >> x;
for(count = x; count != 0; count --)
{
getdata (length, width, costpersqfoot);
InstalledPrice (length, width, costpersqfoot);
totalprice (installation);
if (count ==1)
{
printdata (length, width, price);
}
}
}
void getdata(int & length, int & width, float & costpersqft)
{
cin >> length >> width >> costpersqft;
}
float InstalledPrice (int a, int b, float c)
{
installation = 0;
const float LABOR_COST = 0.35;
float sqfoot;
sqfoot = length * width;
installation = (costpersqfoot * sqfoot) + (LABOR_COST * sqfoot) + installation;
}
float totalprice(float installation)
{
const float TAX_RATE = 0.05;
price = (installation * TAX_RATE) + installation;
}
void printdata(int length, int width, float price)
{
cout << length << " " << width << " " << price << endl;
}
#include <iostream>
#include <time.h>
#include <stdlib.h>
// This program is writen by KHUMBELO DIFFERENCE MUTHAVHINE from Ha- Vhangani . Khumbelo is a programmer
using namespace std;
// call function calculateCarpetSize
void CalculateCarpetSize (int &length, int &width, int &carpetSize)
{
carpetSize = length * width;
}
// call function calculateCarpetCost
void CalculateCarpetCost (int &carpetSize , float &sellingPrice , float &carpetCost )
{
float tax = 0.14;
carpetCost = carpetSize * sellingPrice * tax;
}
// call function calculateLabourCost
CalculateLabourCost(int &carpetSize , int &labour, float &labourCost)
{
labourCost = carpetSize * labour;
}
bool qualifyForDiscount(int &customerNo){
if (customerNo <=9999)
{
void computeDiscount (float &carpetCost );
return true ;
}
else{return false;
}
}
// call function computeDiscount
void computeDiscount (float &carpetCost, float &discountPercentage )
{
cout << "Enter the percetage discout: "<< endl;
cin >> discountPercentage ;
carpetCost = carpetCost * discountPercentage;
}
// call function printCustomerStatement
void printCustomerStatement( )
{
cout.setf(ios::fixed);
cout << endl;
cout << "CROSWELL CARPET STORE" << endl;
cout << "STATEMENT" << endl;
}
int main()
{
int customerNo;
string customerName, customersurname;
float roomLength;
float roomWidth, discountPercentage;
float sellingPrice;
float carpetCost;
float labourCost;
float discount;
int carpetSize;
int rooLength, roonWidth;
int labour = 24;
//float labourCost;
cout.setf(ios::fixed);
cout.precision(2);
cout << "\nPlease enter the following information: ";
cout << "\n Customer FIRST name: ";
cin >> customerName;
cout << "\n Customer LAST name: ";
cin >> customersurname;
cout << "\n Customer number: ";
cin >> customerNo;
cout << "\n The length of the room: ";
cin >> roomLength;
cout << "\n The width of the room: ";
cin >> roomWidth;
cout << "\n The carpet selling price: ";
cin >> sellingPrice;
// call function calculateCarpetSize
CalculateCarpetSize (rooLength, roonWidth, carpetSize);
// call function calculateCarpetCost
CalculateCarpetCost (carpetSize ,sellingPrice, carpetCost );
// call function calculateLabourCost
CalculateLabourCost(carpetSize , labour, labourCost);
if (customerNo<= 9999){
bool qualityForDiscout(customerNo);
computeDiscount (carpetCost, discountPercentage );
}
// call function computeDiscount
// call function printCustomerStatement
// printCustomerStatement(customerName, customerNo, carpetCost, labourCost, discount);
printCustomerStatement();
cout << "\n Customer name: ";
cout << customerName << customersurname<<endl;
cout << "\n Customer number: ";
cout << customerNo <<endl;
cout << "\n The length of the room: ";
cout << roomLength <<endl;
cout << "\n The width of the room: ";
cout<< roomWidth <<endl;
cout << "\n The carpet selling price: ";
cout<< "sellingPrice:" << sellingPrice <<endl;
return 0;
} // end main
В функции
float InstalledPrice (int a, int b, float c)
вы устанавливаете значение установки каждый раз, когда выполняете функцию.
installation = 0;
Попробуйте удалить эту строку и вставить ее перед циклом for в основной функции.
installation = 0;
for(count = x; count != 0; count --)
С константами в вашем коде он напечатает 19.74
((4 * 2) + (4 * 0,35) = 9,4 для каждой комнаты, 18,8 для двух комнат. С налогом (18,8 * 1,05) = 19,74)
Если вы откажетесь от конца функции, возвращающей что-то еще, кроме void
у программы есть неопределенное поведение, то есть она может делать все, что захочет. Производство другой продукции, чем ожидалось, относится к самой мягкой форме, которую она может принять.
Ниже приведены изменения кода, который вы должны:
return
(main()
является исключением, и diesn't абсолютно требует return
хотя возвращает int
но хороший стиль по-прежнему использует return 0;
).Вы должны убедиться, что все входы действительно успешны, например, используя что-то вроде:
if (std::cin >> length >> width >> costpersquarefeet) {
// process the entered data
}
else {
std::cerr << "ERROR: failed to read inoyt!\n";
}
Я бы, вероятно, использовал более подробный chrck, а также рассказал пользователю, какой ввод я ожидаю.
static
переменную внутри функции и каким-то образом получить к ней доступ, вы можете узнать о глобальных переменных, когда вам необходимо, что может быть в довольно будущем). Здесь многое происходит, наиболее важным из которых является обращение к возвращаемым значениям из функций, как сказал @john. С точки зрения только вашей математики, рассмотрите 1 комнату 2ft x 2ft со стоимостью 2 на квадратный дюйм - ваша стоимость installation = (2 * 4) + (.35 * 4) + 0
будет installation = (2 * 4) + (.35 * 4) + 0
на installation = (2 * 4) + (.35 * 4) + 0
, что составляет 9,4, Позже в вашей программе вы добавляете налог, price = 9.4 *.05 + 9.4
, что дает вам 9.87. Не знаете, откуда вы взяли 11.2.