gpt4 book ai didi

c - 将结构数组传递给函数以输入值

转载 作者:太空宇宙 更新时间:2023-11-04 04:46:32 24 4
gpt4 key购买 nike

需要将结构数组传递给 2 个函数,以便用户可以输入值。这是所需的结构:

struct Sale {
double quantity;
double unit_p;
char taxable;
};

调用main函数中的函数为:

no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);

我通过以下方式输入值:

printf("Quantity    : ");
scanf("%lf", &s[i].quantity);
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);

它在 gcc 编译器中编译良好。当我运行程序时,我可以输入值,但是当我尝试打印值时,它显示所有值都为 0。这些值没有存储在结构数组中

我得到的输出:

Quantity    : 2
Unit Price : 1.99
Taxable(y/n) : y

Quantity Unit Price
0.000000 0.000000

完整代码:程序接受这些值并在 2 个单独的函数中计算总价

#include <stdio.h>

const int MAX_SALES = 10;

struct Sale {
double quantity;
double unit_p;
char taxable;
};

void total(const struct Sale *s,int n);
int enter(struct Sale *s, int M);

int main()
{
int no_sales;
struct Sale sales[MAX_SALES];
printf("Sale Records \n");
printf("=============\n");
no_sales = enter(sales, MAX_SALES);
total(sales, no_sales);
}

int enter(struct Sale *s, int M)
{
int i = 0;
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
while(s[i].quantity != 0) {
printf("Unit Price : ");
scanf("%lf", &s[i].unit_p);
printf("Taxable(y/n) : ");
scanf("%*c%c%*c", &s[i].taxable);
i++;
if(i == M) {
printf("Maximum exceeded\n");
break;
}
printf("Quantity : ");
scanf("%lf", &s[i].quantity);
}

int j;
for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}

return i;
}

void total(const struct Sale *s,int n)
{
int i, subtot = 0, hst = 0, tot = 0;
for(i = 0; i < n; i++) {
subtot = subtot + (s[i].quantity * s[i].unit_p);
if(s[i].taxable == 'y' || s[i].taxable == 'Y') {
hst = hst + (0.13 * s[i].quantity * s[i].unit_p);
}
}
tot = subtot + hst;
printf("\n%-12s%.2lf", "Subtotal", subtot);
printf("\n%-12s%.2lf", "HST (13%)", hst);
printf("\n%-12s%.2lf\n", "Total", tot);
}

最佳答案

在函数 enter() 中,您使用了错误的索引变量 i 来访问结构:

for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[i].quantity, s[i].unit_p, s[i].taxable);
}

应该是

for(j = 0; j < i; j++) {
printf("%lf %lf %c\n", s[j].quantity, s[j].unit_p, s[j].taxable);
}

其次,在函数 total() 中,用于计算总计的变量应为 double 类型

int i;
double subtot = 0, hst = 0, tot = 0;
...

关于c - 将结构数组传递给函数以输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319396/

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