问题描述
标题不言自明。我尝试将 quantity
添加到原型参数中,但我认为当我运行程序时数量会增加。我还尝试将 discountRates
添加到原型中,但这也没有任何作用。
#include <iostream>
using namespace std;
/*Writing the prototype*/
double getdiscountRates();
int main()
{
int quantity,discountRates;
float price;
double pretotal,totalAfterdiscount,discountamount;
/* Input Statement */
cout << "Company Order Cost Calculator" << endl << endl;
cout << "How many items does the customer want? ";
cin >> quantity;
cout << "How much does each item cost? $";
cin >> price;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
/* Calling the second function */
discountRates = getdiscountRates();
pretotal = quantity * price;
discountamount = pretotal * discountRates;
totalAfterdiscount = pretotal - discountamount;
/* display result */
cout << endl << "Total Before discount: $" << pretotal << endl;
cout << "discount Amount: $" << discountamount << endl;
cout << "Total After discount: $" << totalAfterdiscount << endl;
return 0;
}
/* Writing the second function */
double getdiscountRates()
{
int discountRates,quantity;
if (quantity <= 8)
{
discountRates = 0;
}
else if ((quantity >= 9) && (quantity <= 12))
{
discountRates = 0.10;
}
else if ((quantity >= 13) && (quantity <= 25))
{
discountRates = 0.15;
}
else
{
discountRates = 0.20;
}
return discountRates;
}
解决方法
您的 getDiscountRates
函数使用未初始化的局部变量 quantity
的不确定值。
您似乎想从 quantity
函数中传递 main
的值。
你应该添加一个参数来传递它。
您还应该将 double
用于局部变量 DiscountRates
。否则,该值将被截断为整数,并且所有情况下的结果都为零。
#include <iostream>
using namespace std;
/*Writing the prototype*/
double getDiscountRates(int quantity); // add argument
int main()
{
// use proper type for DiscountRates
int quantity;
float price;
double DiscountRates,pretotal,totalAfterDiscount,discountamount;
/* Input Statement */
cout << "Company Order Cost Calculator" << endl << endl;
cout << "How many items does the customer want? ";
cin >> quantity;
cout << "How much does each item cost? $";
cin >> price;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
/* Calling the second function */
DiscountRates = getDiscountRates(quantity); // pass the value of quantity
pretotal = quantity * price;
discountamount = pretotal * DiscountRates;
totalAfterDiscount = pretotal - discountamount;
/* Display result */
cout << endl << "Total Before Discount: $" << pretotal << endl;
cout << "Discount Amount: $" << discountamount << endl;
cout << "Total After Discount: $" << totalAfterDiscount << endl;
return 0;
}
/* Writing the second function */
double getDiscountRates(int quantity) // add argument
{
double DiscountRates; // remove the local variable quantity and use proper type for DiscountRates
if (quantity <= 8)
{
DiscountRates = 0;
}
else if ((quantity >= 9) && (quantity <= 12))
{
DiscountRates = 0.10;
}
else if ((quantity >= 13) && (quantity <= 25))
{
DiscountRates = 0.15;
}
else
{
DiscountRates = 0.20;
}
return DiscountRates;
}