我正在使用C中的函数。如果我想返回void taxCalculator(),代码会是什么样子?以int main()为浮点数,因此可以在那里打印。
这就是代码的样子:
顶部的定义
void taxCalculator(float income, float tax);
主要功能:
int main(void){
float income, tax;
printf("Enter the amount of income: ");
scanf("%f", &income);
taxCalculator(income, tax);
}
taxCalculator功能:
void taxCalculator(float income, float tax)
{
if( income < 750.00f){
tax = income * 0.01f;
}else if (income <= 2250.00f){
tax = 7.50f + (income - 750) * 0.02f;
}else if (income <= 3750.00f){
tax = 37.50f + (income - 2250) * 0.03f;
}else if (income <= 5250){
tax = 82.50f + (income - 3750) * 0.04f;
}else if (income <= 7000){
tax = 142.50f + (income - 5250) * 0.05f;
}else if(income > 7000.00f){
tax = 230.00f + (income - 7000) * 0.06f;
}
printf("The amount of tax: %.2f", tax);
}
答案 0 :(得分:4)
你可以这样吗
float taxCalculator(float income) {
...
return tax;
}
...
printf("The amount of tax: %.2f", taxCalculator(income));
当函数执行时,当它终止时,它将被替换为其返回值,因此printf()
将使用该值进行打印。
完整示例:
#include <stdio.h>
float taxCalculator(float income) {
float tax;
if (income < 750.00f) {
tax = income * 0.01f;
} else if (income <= 2250.00f) {
tax = 7.50f + (income - 750) * 0.02f;
} else if (income <= 3750.00f) {
tax = 37.50f + (income - 2250) * 0.03f;
} else if (income <= 5250) {
tax = 82.50f + (income - 3750) * 0.04f;
} else if (income <= 7000) {
tax = 142.50f + (income - 5250) * 0.05f;
} else if (income > 7000.00f) {
tax = 230.00f + (income - 7000) * 0.06f;
}
return tax;
}
int main(void) {
float income = 2250;
printf("The amount of tax: %.2f", taxCalculator(income));
return 0;
}
答案 1 :(得分:0)
您可以将税收返回到传递给函数的内存位置:
void taxCalculator(float income, float * ptax)
{
float tax;
... // init tax here
printf("The amount of tax: %.2f", tax);
*ptax = tax;
}
这样称呼:
int main(void)
{
float income, tax;
...
taxCalculator(income, &tax);
...
然后您可以自由使用返回值作为错误指示符:
#include <errno.h>
#include ...
int taxCalculator(float income, float * ptax)
{
float tax;
if ((0. > income) || (NULL == ptax))
{
errno = EINVAL;
return -1;
}
... // init tax here
*ptax = tax;
return 0;
}
并像这样称呼它
int result = taxCalculator(income, &tax);
if (-1 == result)
{
perror("taxCalculator() failed");
}
else
{
printf("The amount of tax: %.2f", tax);
}