下面只是我正在处理的一个简单程序,我需要获取所有printf并在指令中对其进行定义。
#include <stdio.h>
#define name(parameter) printf("......")
main(){
...
}
我该怎么做?
#include <stdio.h>
#define FICA_PERCENTAGE 0.0765
#define HOURS_WORKED(int hours_worked) printf("\nHours Worked: %d\n", hours_worked)
#define HOURLY_RATE(float hourly_rate) printf("Hourly Rate: $%5.2f\n", hourly_rate)
#define GROSS_PAY(float gross_pay) printf("Gross PAy: $%5.2f\n", gross_pay)
#define FICA_DEDUCTION(float fica_deduction) printf("FICA deduction: $%5.2f\n", fica_deduction)
#define NET_PAY(float net_pay) printf("Net Pay: $%5.2f\n", net_pay)
main(){
int hours_worked;
float hourly_rate, gross_pay, net_pay,fica_deduction;
printf("Simple Payroll Program: \n");
printf("-------------------\n");
printf("Enter the number of hrs workrd: ");
scanf("%d", &hoursWorked);
printf("Enter the hourly rte of pay: ");
scanf("%f", &hourly_rate);
gross_pay = hoursWorked * hourly_rate;
fica_deduction = gross_pay * FICA_PERCENTAGE;
net_pay = gross_pay - fica_deduction;
HOURS_WORKED;
HOURLY_RATE;
GROSS_PAY;
FICA_DEDUCTION;
NET_PAY;
/*printf("\nHours Worked: %d\n", hoursWorked);
printf("Hourly Rate: $%5.2f\n", hourly_rate);
printf("Gross PAy: $%5.2f\n", gross_pay);
printf("FICA deduction: $%5.2f\n", fica_deduction);
printf("Net Pay: $%5.2f\n", net_pay);*/
return 0;
}
#include <stdio.h>
#define FICA_PERCENTAGE 0.0765
main(){
int hours_worked;
float hourly_rate, gross_pay, net_pay,fica_deduction;
printf("Simple Payroll Program: \n");
printf("-------------------\n");
printf("Enter the number of hrs workrd: ");
scanf("%d", &hoursWorked);
printf("Enter the hourly rte of pay: ");
scanf("%f", &hourly_rate);
gross_pay = hoursWorked * hourly_rate;
fica_deduction = gross_pay * FICA_PERCENTAGE;
net_pay = gross_pay - fica_deduction;
printf("\nHours Worked: %d\n", hoursWorked);
printf("Hourly Rate: $%5.2f\n", hourly_rate);
printf("Gross PAy: $%5.2f\n", gross_pay);
printf("FICA deduction: $%5.2f\n", fica_deduction);
printf("Net Pay: $%5.2f\n", net_pay);
return 0;
}
答案 0 :(得分:0)
宏执行替换,并带有可选的参数替换
#define X yyyy
将用X
替换令牌yyyy
的出现。
#define X(Y) yyyy Y yyyy
将用X(Foo)
替换参数化令牌yyyy Foo yyyy
的出现。
以您的第一次printf
尝试为例,看来您想要这样做:
#define HOURS_WORKED(Y) \
printf("\nHours Worked: %d\n", Y)
然后,您将这样称呼它:
HOURS_WORKED(hoursWorked);
您需要对其他宏和调用进行相应的调整。
答案 1 :(得分:0)
这不是宏的好用例。它只会混淆您的代码,并在不需要的地方增加一些复杂性。但是,如果您致力于此,则需要进行一些更改。
首先,宏参数没有类型:
#define HOURS_WORKED(hours_worked) printf("\nHours Worked: %d\n", hours_worked)
第二,在调用宏时,还需要提供参数:
HOURS_WORKED(hoursWorked);
请记住,类似函数的宏不是函数-它们只是文本替换。不评估宏参数,它们只是在适当位置扩展。也就是说,如果您将HOURS_WORKED
调用为
HOURS_WORKED(n * 40);
然后它将扩展为
printf("\nHours Worked: %d\n", n * 40)
为避免优先级和解析问题,将宏参数包装在parens中通常是一个好主意:
#define HOURS_WORKED(hours_worked) printf("\nHours worked: %d\n", (hours_worked) );