c++引用参数函数

c++ reference parameters function

本文关键字:函数 参数 引用 c++      更新时间:2023-10-16

我不知道为什么这个程序不能运行。getStockInfo中的值应该存储在引用参数中。然后displayStatus接受它们作为参数。我知道这与getStockInfo和displayStatus有关,当它们被定义时,我就是搞不清

#include <iostream>
#include <iomanip>
using namespace std;
void getStockInfo(int &, int&, double&);
void displayStatus(int, int, double, double);
int main()
{
//Declare Variables
int orderedSpools;
int spoolsStock;
double specialCharges;
int spoolsOrdered;
int backOrder;
double subtotal,
       shipping,
       total;

cout << "Middletown Wholesale Copper Wire Company" << endl;
getStockInfo(spoolsOrdered, spoolsStock, specialCharges);
displayStatus(spoolsOrdered, spoolsStock, specialCharges);
  system("pause");
  return 0;
}
void getStockInfo(int &spoolsOrdered, int &spoolsStock, double &specialCharges)
{
char ship; 
cout << "How many spools would you like to order: ";
cin >> spoolsOrdered;
//Validate the spools ordered 
while(spoolsOrdered < 1)
{
    cout << "Spools ordered must be at least one" << endl;
    cin >> spoolsOrdered;
}
cout << "How many spools are in stock: ";
cin >> spoolsStock;
//Validate spools in stock
while(spoolsStock < 0)
{
    cout << "Spools in stock must be at least 0" << endl;
    cin >> spoolsStock;
}
cout << "Are there any special shipping charges? ";
cout << "Enter Y for yes or another letter for no: ";
cin >> ship;
//Validate special charges
if(ship == 'Y' || ship == 'y')
{
    cout << "Enter the special shipping charge: $";
    cin >> specialCharges;
}
else
{
    specialCharges = 10.00;
}
}
void displayStatus(int spoolsOrdered, int spoolsStock, double specialCharges,
                   double total)
{
double backOrder,
       subtotal,
       shipping,
       total;
int itemsReady;

cout << "Items ordered: " << spoolsOrdered << endl;
cout << "Items ready to ship: " << spoolsStock << endl;

if(spoolsOrdered > spoolsStock)
{
    backOrder = spoolsOrdered - spoolsStock;
    cout << "Items on backorder: " << backOrder << endl;
}

subtotal = itemsReady * 100;
cout << "Subtotal: " << subtotal << endl;
shipping = specialCharges;
cout << "Shipping: " << shipping << endl;
total = subtotal + shipping;
cout << "Total Due: " << total << endl;

}

以下是您如何声明displayStatus:

void displayStatus(int, int, double, double);

以下是如何使用displayStatus:

displayStatus(spoolsOrdered, spoolsStock, specialCharges);

你觉得有什么不同吗

提示:计算每行中的参数数量。

void displayStatus(int spoolsOrdered, int spoolsStock, double specialCharges,
                   double total)  //**<-- here: total as parameter**
{
double backOrder,
       subtotal,
       shipping,
       total;  //**<-- and here: total as local variable**
int itemsReady;

在上面的代码中,我发现你有一个冗余。我在上面做了标记。您有两个同名的变量,total,一个是displayStatus函数的参数,另一个是display Status函数的局部变量。

当我逐行看到你的代码时,这个total变量在main函数和getStockInfo函数中都没有执行任何计算。total变量的唯一计算发生在displayStatus函数中。因此,我建议您最好删除displayStatus函数参数上的变量total。这不会损害您的代码,因为您已经有了本地变量total

EDIT:您不需要主函数中的total变量,因此,删除此变量。