gpt4 book ai didi

在 C 中将函数作为 float 调用

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:18 25 4
gpt4 key购买 nike

我正在使用 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;
}

关于在 C 中将函数作为 float 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com