You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环打印scanf读取的数据失败:代码仅输出最后一项求助

嘿,这个问题我太熟悉啦!你现在的代码里只用了单个变量来存商品名称和价格,每次输入新的商品时,旧的数据都会被直接覆盖掉,所以最后打印的时候当然只能看到最后一项啦~

核心问题分析

你定义的item(哦对了,你原代码里没声明item变量,这也是个小bug哦)和price都是单个变量,它们同一时间只能保存一组数据。循环输入时,新的商品名和价格会把之前的内容彻底替换,最后自然只剩最后一次输入的信息。

解决方案:用数组存储多组数据

我们可以用数组来分别存储所有商品的名称和价格,这样每一项数据都能被保留下来。下面是修改后的完整可运行代码:

#include <stdio.h>
#include <string.h> // 处理字符串需要的头文件

int main() {
    int a, item_amount;
    // 定义数组:假设最多支持100件商品,可按需调整大小
    char items[100][50]; // 二维字符串数组:每行存一个商品名,最多50个字符
    float prices[100];   // 浮点数组存对应商品的价格

    printf("How many item do you want: ");
    scanf("%i", &item_amount);
    getchar(); // 清空输入缓冲区的换行符,避免干扰后续输入

    for(a=1; a<= item_amount; a = a + 1) {
        printf("Item %i: ", a);
        // 用fgets读取带空格的商品名,比scanf("%s")更实用
        fgets(items[a-1], sizeof(items[a-1]), stdin);
        // 去掉fgets自动读取的换行符
        items[a-1][strcspn(items[a-1], "\n")] = '\0';
        
        printf("Price: RM ");
        scanf("%f", &prices[a-1]);
        getchar(); // 再次清空缓冲区,准备下一次输入商品名
    }

    // 打印格式化收据
    printf("\n===== 购物收据 =====\n");
    for(a=1; a<= item_amount; a = a + 1) {
        printf("Item %i: %s\n", a, items[a-1]);
        printf("Price: RM %.2f\n\n", prices[a-1]); // 保留两位小数,符合货币显示习惯
    }

    return 0;
}

关键修改点说明

  • 把单个变量改成数组:items存储所有商品名,prices存储对应价格,数组索引对应商品序号(注意数组从0开始,所以用a-1来对应)
  • 用fgets替代scanf("%s"):这样可以读取带空格的商品名(比如"Chocolate Cake"不会被截断)
  • 清空输入缓冲区:每次用scanf读取数字后,缓冲区会留下换行符,getchar()可以避免它干扰下一次字符串输入
  • 格式化价格输出:用%.2f让价格显示两位小数,更符合收据的实际需求
进阶方案:用结构体让代码更规范

如果想让代码逻辑更清晰,还可以用结构体把商品的名称和价格封装在一起,方便后续扩展(比如添加商品数量、编号等字段):

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

// 定义商品结构体,把相关字段打包
typedef struct {
    char name[50];
    float price;
} Product;

int main() {
    int a, item_amount;
    Product products[100]; // 结构体数组存储多个商品

    printf("How many item do you want: ");
    scanf("%i", &item_amount);
    getchar();

    for(a=1; a<= item_amount; a = a + 1) {
        printf("Item %i: ", a);
        fgets(products[a-1].name, sizeof(products[a-1].name), stdin);
        products[a-1].name[strcspn(products[a-1].name, "\n")] = '\0';
        
        printf("Price: RM ");
        scanf("%f", &products[a-1].price);
        getchar();
    }

    // 打印收据并计算总价
    printf("\n===== 购物收据 =====\n");
    float total = 0.0;
    for(a=1; a<= item_amount; a = a + 1) {
        printf("Item %i: %s\n", a, products[a-1].name);
        printf("Price: RM %.2f\n\n", products[a-1].price);
        total += products[a-1].price;
    }
    printf("总金额: RM %.2f\n", total);

    return 0;
}

这个版本不仅能正确打印所有商品,还能顺便计算总金额,实用性更强~

内容的提问来源于stack exchange,提问作者Sarah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:46