繁体   English   中英

在C中以浮点形式调用函数

[英]Calling the function as a float in C

我正在使用C中的函数。如果我想返回void taxCalculator(),代码将是什么样子? 将int main()转换为float,因此可以将其打印在那里。

代码如下所示:

顶部的定义

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);

}

你可以这样

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;
}

您可以通过将结果写到传递给函数的内存位置来退税:

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);
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM