我正在写一个程序,根据婚姻状况,14岁以下的孩子数量,毛收入和贡献给养老基金的毛收入的百分比来计算税收。一切似乎都是正确的,但婚姻状况、孩子数量、工资总额和养老基金百分比在我的函数taxAmount中看不到。我认为使用与号(&)可以让我的其他函数查看这些值。我不能改变我拥有的函数的数量,我必须坚持我目前正在使用的两个函数。对于如何解决我的问题,有人有什么建议吗?错误消息指出婚姻、子女、grossSalary和养老金未在作用域中声明。
原型是:
void getData(char&, int&, int&, int&);
int taxAmount(int);我的主要功能是:
int main()
{
char marital;
int children;
int grossSalary;
int pension;
int amount;
getData(marital, children, grossSalary, pension);
cout << "The tax amount is: $" << taxAmount(amount) << endl;
_getch();
return 0;
}我的获取数据的函数:
void getData(char& marital, int& children, int& grossSalary, int& pension)
{
cout << "Enter your marital status. Enter 'm' for married. Enter 's' for";
cout << " single. \n";
cin >> marital;
cout << endl;
cout << "Enter the number of children you have under the age of 14. \n";
cin >> children;
cout << endl;
cout << "Enter your gross salary. If you are married, enter the combined";
cout << " income of you and your spouse.";
cin >> grossSalary;
cout << endl;
cout << "Enter the number of the percentage (up to 6) of your gross";
cout << " income contributed to a pension fund.";
cin >> pension;
cout << endl;
}我的计算金额的函数(删除代码):
int taxAmount(int amount)
{
...
}发布于 2015-03-05 05:50:55
如果您可以将taxAmount的函数签名修改为:
int taxAmount(int amount, char marital, int children, int grossSalary, int pension)然后,这将是将参数放入函数的最好方法;或者,为了省去输入,创建一个包含所有4个值的类,并只需传递一个常量引用到您的类:
struct TaxRecord {
char marital;
int children;
int grossSalary;
int pension;
};..。
int taxAmount(int amount, const TaxRecord &record);另一方面,如果你也不能更改函数签名,那么我建议你将你的4个值设置为文件范围,而不是main函数的函数范围:
static char marital;
static int children;
static int grossSalary;
static int pension;
int main(int argc, char *argv[]) {
// ...
}您需要在C++中使用static关键字,因为否则您的变量将默认为external;如果使用C语言,您可以删除static关键字,因为这是默认关键字(尽管请参阅下面@wallyk的注释)。
这里假设在同一个.c/.cpp文件中定义了main和taxAmount。如果不是,您应该这样做:
tax.hpp:
extern char marital;
extern int children;
extern int grossSalary;
extern int pension;在tax.cpp中,并且仅在tax.cpp中:
#include "tax.hpp"
char marital;
int children;
int grossSalary;
int pension;这样,每个翻译单元(cpp文件)都可以访问这4个变量。但在文件范围内保持它们的静态要干净得多,因为名称不会污染整个可执行文件,只会污染一个文件。
https://stackoverflow.com/questions/28865252
复制相似问题