【问题标题】:passing struct array to function for inputting value将结构数组传递给函数以输入值
【发布时间】:2013-12-02 01:15:40
【问题描述】:

需要将结构数组传递给 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);
}

【问题讨论】:

  • 如何打印它们?显示打印变量的代码。还要添加结构的定义。
  • 如何创建Sale 的数组?
  • 目前,我在您的上一个 scanf() 中发现了一些问题。它使用的格式要求提供多个变量,甚至...字段分隔符?
  • 最后一个 scanf 正在接受一个字符,所以我想丢弃输入缓冲区中的数据,这就是我使用 2 %*c
  • 。我可以输入值,但它没有被保存到数组中。通过引用传递结构数组的正确方法是什么?

标签: c arrays struct


【解决方案1】:

在函数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;
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2019-05-09
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多