gpt4 book ai didi

c - 在c中累积数组

转载 作者:行者123 更新时间:2023-11-30 18:55:08 26 4
gpt4 key购买 nike

我正在尝试用 C 创建一个发票程序,但它没有按照我的预期进行。

这是我的代码:

#include <stdio.h>
#include <string.h>


int main()
{
int choice;
char item_name[1000][3][20];
float item_price[1000][3];
float quantity[1000][3];
int k;
int j;


k=0;
j=0;
for (k=0;k<1000;k++)
{
printf ("\n");
printf ("Enter the item name: ");
scanf ("%s", item_name[k][j]);
printf ("\n");
printf ("Enter the item price: ");
scanf ("%f", &item_price[k][j]);
printf ("\n");
printf ("Enter the item quantity: ");
scanf ("%f", &quantity[k][j]);
printf ("\n");

printf ("| Quantity | Item Name | Item Price |");
printf ("\n");

for (j=0;j<1000;j++)
{
if (quantity[k][j]==0) break;
printf (" %.1f", quantity[k][j]);
printf (" %s", item_name[k][j]);
printf (" %.2f", item_price[k][j]);
printf ("\n\n");
}

printf (" Would you like to enter another item? Enter '1' for yes and '2' for no: ");
scanf ("%d", &choice);
printf ("\n");

if (choice == 2) break;
if (k>999) break;
}
return 0;
}

这是我想要的输出:

Enter item name: Chips
Enter item price: 0.70
Enter item quantity: 3

| Quantity | Item Name | Item Price |
3 Chips 0.70

Would you like to enter another item? Enter '1' for yes and '2' for no: 1
Enter item name: Drinks
Enter item price: 1.00
Enter item quantity: 3

| Quantity | Item Name | Item Price |
3 Chips 0.70
3 Drinks 1.00

Would you like to enter another item? Enter '1' for yes and '2' for no: 2

最佳答案

我认为你最好使用链接列表并将所有项目信息放入结构中,如下所示

typedef struct ItemData
{
char *name;
float price;
float quantity;
} ItemData_t;

但请注意,对于名称,您必须在将字符串存储在其中之前分配一些内存。看看链表是如何工作的,它非常简单,尤其是对于指针。

关于c - 在c中累积数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28635037/

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