c-按值传递和按引用传递
作者:互联网
我正在开发一个项目,该项目通过使用超载为员工计算收入,并且还通过引用传递值.我需要使用程序中的至少一个函数来演示传递值;以及至少一个用于演示带有引用参数的引用传递的功能.这是到目前为止我得到的:
#include <iostream>
#include "Grosspay.h"
#include "iomanip"
using namespace std;
double income(double hours, double payrate)
{
double grosspay = 0;
double federaltax = .10;
double statetax = .05;
double totaltax;
double netpay;
if (hours <= 40)
{
grosspay = payrate * hours;
}if (hours > 40 && hours <= 50)
{
grosspay = (payrate * 40) + ((hours - 40) * payrate * 1.5);
}
if (hours > 50)
{
grosspay = (payrate * 40) + (10 * payrate * 1.5) + ((hours - 50) * payrate * 2);
}
cout << "Grosspay weekly is: " << grosspay << endl;
federaltax = grosspay * .10;
cout << "Federal Tax is: " << federaltax << endl;
statetax = grosspay * .05;
cout << "State Tax is: " << statetax << endl;
totaltax = federaltax + statetax;
cout << "Total tax is: " << totaltax << endl;
netpay = grosspay - totaltax;
return (netpay);
}
double income(const double &year)
{
double grosspay;
double federaltax = .10;
double statetax = .05;
double totaltax;
double netpay;
grosspay = year / 52;
cout << "Grosspay weekly is: " << grosspay << endl;
federaltax = grosspay * .10;
cout << "Federal Tax is: " << federaltax << endl;
statetax = grosspay * .05;
cout << "State Tax is: " << statetax << endl;
totaltax = federaltax + statetax;
cout << "Total Tax is: " << totaltax << endl;
netpay = grosspay - totaltax;
return (netpay);
}
void Grosspay::determineGrosspay()
{
cout << "Enter 1 - Calculate payroll for hourly employee" << endl;
cout << "Enter 2 - Calculate payroll for salary employee" << endl;
cout << "Enter 3 - Exit" << endl;
cout << "Federal Tax is 10% of Grosspay" << endl;
cout << "State Tax is 5% of Grosspay" << endl;
while (choice != 3)
{
cout << "\nEnter your choice: " << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter employee ID: " << endl;
cin >> ID;
cout << "Enter hours: " << endl;
cin >> hours;
cout << "Enter payrate: " << endl;
cin >> payrate;
cout << "Employee ID: " << ID << endl;
cout << setprecision(2) << fixed;
cout << "The net pay for hourly employee: " << income(hours, payrate) << endl;
break;
case 2:
cout << "Enter employee ID: " << endl;
cin >> ID;
cout << "Enter salary: " << endl;
cin >> year;
cout << "Employee ID: " << ID << endl;
cout << setprecision(2) << fixed;
cout << "The net pay for salaried employee: " << income(year) << endl;
break;
case 3:
cout << "Exited program" << endl;
break;
default:
cout << "Please try again!" << endl;
break;
}
}
}
这里的一位天才告诉我,我需要将双倍收入(const double& year)作为转介参考.但是我不太确定到底有什么区别!我仍然有相同的输出.谁能帮帮我吗?
解决方法:
以下是一些准则:
>如果值适合处理器的寄存器和
该参数将不会被修改.
>如果功能会修改参数,则按引用传递.
>如果对象大于
处理器的寄存器和参数将不会被修改.
对double,float,int,char和bool之类的类型传递常量引用没有意义,因为它们通常适合处理器的字长.编译器将尝试将这些值传递到寄存器中.这些POD类型没有额外的复制成本.因此,按值传递(需要较少的键入).
标签:c,pass-by-reference,pass-by-value 来源: https://codeday.me/bug/20191012/1898435.html