我有这段代码。
int a, item_amount;
float price;
printf("How many item do you want: ");
scanf("%i", &item_amount);
for(a=1; a<= item_amount; a = a + 1)
{
printf("Item %i: ", a);
scanf("%s", item);
printf("Price: RM ");
scanf("%f", &price);
}
for(a=1; a<= item_amount; a = a + 1)
{
printf("\nItem: %s",item);
printf("\nPrice: %f", price);
}
问题是,我正在尝试打印出商品的名称和价格作为收据,但它只打印出最后一件商品和价格。输出将显示如下:
How many item do you want: 2
Item 1: Box
Price: 12.20
Item 2: Book
Price: 2.30
(收据将显示如下)
Item: Book
Price: 2.30
Item: Book
Price: 2.30
如何让它打印所有已扫描的项目而不重复上面的项目?
答案 0 :(得分:2)
您需要将值保存在数组中,这样就不会在下一个循环中覆盖以前的值 - 例如:
int a, item_amount;
float price[10]; // array - max 10 elements
char item[10][256]; // array - max 10 elements - max 255 chars in name
printf("How many item do you want: ");
scanf("%i", &item_amount);
for (a = 0; a < item_amount; a = a + 1) // Start from zero
{
printf("Item %i: ", a+1);
scanf("%s", item[a]); // Never use %s - see below
printf("Price: RM ");
scanf("%f", &price[a]);
}
for (a = 0; a < item_amount; a = a + 1) // Start from zero
{
printf("\nItem: %s",item[a]);
printf("\nPrice: %f", price[a]);
}
请注意,上面的代码错过了很多你应该做的检查。例如:
始终检查scanf
永远不要scanf("%s", ...)
它可能导致溢出。使用fgets
或至少执行scanf("%255s...
还要考虑如果用户输入的名称超过255个字符会发生什么......
检查项目数量是否小于或等于10.