需要将struct数组传递给2个函数,以便用户可以输入值。 这是所需的结构:
struct Sale {
double quantity;
double unit_p;
char taxable;
};
将主要功能调用为:
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.值不存储在struct array中
输出我得到了:
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);
}
答案 0 :(得分:0)
在函数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;
...