day6 homework: 函数调用实现纳税计算的静态内存问题

This commit is contained in:
flykhan 2023-07-11 10:30:30 +08:00
parent b931a3f5fe
commit 1ad50f4df7
1 changed files with 18 additions and 12 deletions

View File

@ -15,33 +15,39 @@
// 全月应纳税额超过80000元 45 % // 全月应纳税额超过80000元 45 %
// 13505 // 13505
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> // 用于 malloc 函数调用
void *result(int, double *, int *); // int outNums[2]; // 3.全局地址?为什么要全局地址
int *result(int, float *, int *);
int main() int main()
{ {
int pretexIncome; // 税前收入 int pretexIncome; // 税前收入
double rates[8] = {0, 0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45}; // 税率数组 float rates[8] = {0, 0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45}; // 税率数组
int deducts[8] = {0, 0, 105, 555, 1005, 2755, 5505, 13505}; // 速算扣除数数组 int deducts[8] = {0, 0, 105, 555, 1005, 2755, 5505, 13505}; // 速算扣除数数组
printf("请输入你的税前收入: "); printf("请输入你的税前收入: ");
scanf("%d", &pretexIncome); scanf("%d", &pretexIncome);
result(pretexIncome, rates, deducts); int *res;
res = result(pretexIncome, rates, deducts);
printf("你最后的所得为 %d ,你所缴纳的税额为 %d\n", res[0], res[1]);
// int *res = result(pretexIncome, rates, deducts); free(res); // 释放手动分配的内存空间
// printf("%d%d", res[0], res[1]);
// printf("你最后的所得为 %d ,你所缴纳的税额为 %d\n", result(pretexIncome, rates, deducts)[1], result(pretexIncome, rates, deducts)[0]);
return 0; return 0;
} }
void *result(int pretexIncomeArgs, double *rateArgs, int *deductArgs) int *result(int pretexIncomeArgs, float *rateArgs, int *deductArgs)
{ {
int level; // 税率等级 int level; // 税率等级
int tex; // 缴纳税额 int tex; // 缴纳税额
int aftertexIncome; // 税后收入 int aftertexIncome; // 税后收入
int diff = pretexIncomeArgs - 3500; // 征税差值 int diff = pretexIncomeArgs - 3500; // 征税差值
// static int outNums[2]; // 1.静态地址?为什么要静态地址 (静态变量会放在全局区,仅会在程序结束时释放)
int *outNums = (int *)malloc(2 * sizeof(int *)); // 2.手动分配内存空间?为什么
if (diff <= 0) if (diff <= 0)
level = 0; level = 0;
else if (diff > 0 && diff <= 1500) else if (diff > 0 && diff <= 1500)
@ -62,8 +68,8 @@ void *result(int pretexIncomeArgs, double *rateArgs, int *deductArgs)
tex = diff * rateArgs[level] - deductArgs[level]; tex = diff * rateArgs[level] - deductArgs[level];
aftertexIncome = pretexIncomeArgs - tex; aftertexIncome = pretexIncomeArgs - tex;
printf("你最后的所得为 %d ,你所缴纳的税额为 %d\n", aftertexIncome, tex); outNums[0] = aftertexIncome;
outNums[1] = tex;
// int outNums[2] = {(int *)aftertexIncome, (int *)tex}; return outNums; // 返回结果数组
// return *outNums; // 返回结果数组
} }