我正在尝试用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
答案 0 :(得分:2)
我认为您最好使用链接列表并将所有项目信息放入结构中,如此
typedef struct ItemData
{
char *name;
float price;
float quantity;
} ItemData_t;
但请注意,对于名称,您必须在将字符串存储在那里之前分配一些内存。 查看链接列表的工作方式,非常简单,尤其是指针。
答案 1 :(得分:0)
不需要[3]
在for k循环中只是参考[k]
在for j循环中只需参考[j]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int choice;
char item_name[1000][20];
float item_price[1000];
float quantity[1000];
int k;
int j;
k=0;
j=0;
for (k=0;k<1000;k++)
{
printf ("\n");
printf ("Enter the item name: ");
scanf ("%19s", item_name[k]);
printf ("\n");
printf ("Enter the item price: ");
scanf ("%f", &item_price[k]);
printf ("\n");
printf ("Enter the item quantity: ");
scanf ("%f", &quantity[k]);
printf ("\n");
printf ("| Quantity | Item Name | Item Price |");
printf ("\n");
for (j=0;j<=k;j++)
{
printf (" %.1f", quantity[j]);
printf (" %s", item_name[j]);
printf (" %.2f", item_price[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;
}