如何在C ++中正确传递这些函数值

时间:2014-09-21 19:01:39

标签: c++ function

我正在尝试使用计算县税,销售税的函数编写程序,将它们一起添加,然后在main中输出。我也创建了一个printData函数,所以我可以一次输出所有内容,但由于运行时的初始化错误,我对如何使用它感到困惑。我的功能不是很好,希望能得到一些帮助。

这是我的书面代码:(已更新)

#include <iostream>

using namespace std;

void calcCounty(double &TotalSales, double &CountySalesTax);
void calcState(double &TotalSales, double &StateSalesTax);
void calcTotal(double &TotalSales, double &CountySalesTax, double &StateSalesTax);
void printData(double &TotalSales, double &CountySalesTax, double &StateSalesTax);

double TotalSales;
double CountySalesTax;
double StateSalesTax;

int main()
{

    cout << "Tax Calculation program" << endl;
    cin >> TotalSales;
    printData(TotalSales, CountySalesTax, StateSalesTax);
    cout << TotalSales << CountySalesTax << StateSalesTax;
    return 0;
}

void calcCounty(double &TotalSales, double &CountySalesTax)
{
    CountySalesTax = TotalSales * 0.4;
}

void calcState(double &TotalSales, double &StateSalesTax)
{
    StateSalesTax = TotalSales * 0.2;
}

void calcTotal(double &TotalSales, double &CountySalesTax, double &StateSalesTax)
{
    TotalSales = CountySalesTax + StateSalesTax;
}

void printData(double &TotalSales, double &CountySalesTax, double &StateSalesTax)
{
    cout << TotalSales, CountySalesTax, StateSalesTax;
}

2 个答案:

答案 0 :(得分:0)

您需要首先初始化变量(您需要的变量)。

例如,这个函数:

void calcCounty(double &TotalSales, double &CountySalesTax)
{
    CountySalesTax = TotalSales * 0.4;
}

应该在调用之前初始化TotalSales

根据评论的建议,您还需要在某些时候调用函数。

此外,在您的情况下,打印应该像这样:

cout << TotalSales << ", " << CountySalesTax << ", " << StateSalesTax;

首先,我建议你阅读这个例子:

#include <iostream>

using namespace std;

/*
 * Write a program, which will declare two variables, 'a' and 'b'.
 * They will be initialized with the values 10 and 100, respectively.
 * Write a function 'int find_min(int a, int b)`, which will find
 * which of the given parameters is less and will return it.
 *
 * Then, write `void find_min_no_return(int a, int b, int& min)`,
 * which will do the same job as `find_min()`, but with no return
 * statement.
 */

int find_min(int a, int b) {
  if(a < b) {
    return a;
  }
  else {
    return b;
  }
}

/*
 * 'min' is passed by reference because it is
 * going to be modified. 'a' and 'b' are passed
 * by value.
 */
void find_min_no_return(int a, int b, int& min) {
  if(a < b) {
    min = a;
  }
  else {
    min = b;
  }
}

int main() {
  int a = 10;
  int b = 100;

  int min;

  min = find_min(a, b);
  cout << "min of first function called = " << min << endl;

  find_min_no_return(a, b, min);
  cout << "min of second function called = " << min << endl;

  return 0;
}

然后解决您的问题。

答案 1 :(得分:0)

为什么不宁愿从函数中返回一个值?

double calcCounty(double& totalSales) {
return totalSales * 0.4;
}

然后在你的主要做:

countySalesTax = calcCounty(totalSales);