C语言杂货计算器代码异常求助:输出不符预期如何修复?
你的代码有几个明显的问题,导致输出结果不符合预期,逐个说明修复方法:
1. 总和计算用错了数组(最核心的错误)
在calculateTotalCost函数里,你定义了一个未初始化的int itemCounts[50]数组,还拿它来累加总费用——这完全错了。你应该用传入的itemCosts数组(也就是你在主函数里输入的商品价格数组)。未初始化的数组里都是随机的垃圾值,这就是总费用乱跳的根本原因。
修复后的计算函数:
float calculateTotalCost(float* itemCosts, int itemCount) { float totalCost = 0; int i; for (i = 0; i < itemCount; ++i) { totalCost += itemCosts[i]; } return totalCost; }
2. 读取用户选择时的缓冲区残留问题
输入商品价格后,你用scanf("%f", ...)读取数字,但输入时按下的回车键(换行符\n)会留在输入缓冲区里。接下来的scanf("%c", &choice)会直接读取这个换行符,导致choice的值变成'\n',循环直接终止,根本没法继续添加商品。
修复方法:在读取choice的scanf前面加个空格,让它自动跳过缓冲区里的空白字符(包括换行符):
scanf(" %c", &choice);
3. 循环条件判断逻辑错误
choice是单个字符类型(char),但你用choice == 'yes' || choice == 'Yes'来判断——这明显不对,'yes'是字符串,不是单个字符,编译器其实会把'yes'当成一个多字符常量,完全不符合你的需求。
修复方法:改成判断单个字符,比如用户输入的'y'或'Y':
} while (choice == 'y' || choice == 'Y');
如果想支持用户输入完整的"yes"/"Yes",就得把choice改成字符串数组,比如char choice[10];,然后用strcmp函数判断(记得加#include <string.h>头文件):
char choice[10]; // ... scanf("%s", choice); } while (strcmp(choice, "yes") == 0 || strcmp(choice, "Yes") == 0);
4. 字符串字面量的换行写法错误
原代码里printf("Welcome to Grocery Shop\n");的写法有误(你直接在字符串里换行了),C语言里字符串字面量不能直接换行,必须用\n表示换行符,否则会编译报错。
修复后:
printf("Welcome to Grocery Shop\n");
完整修复后的代码
#include <stdio.h> float calculateTotalCost(float* itemCosts, int itemCount); int main() { int itemCount = 0; float itemCosts[50]; char itemName[50]; char choice; printf("Welcome to Grocery Shop\n"); do { printf("Enter item name: "); scanf("%s", itemName); printf("Enter cost for %s: RM", itemName); scanf("%f", &itemCosts[itemCount]); itemCount++; printf("Do you want to add another item?(y/n): "); scanf(" %c", &choice); } while (choice == 'y' || choice == 'Y'); float totalCost = calculateTotalCost(itemCosts, itemCount); printf("\nTotal cost: RM%.2f\n", totalCost); return 0; } float calculateTotalCost(float* itemCosts, int itemCount) { float totalCost = 0; int i; for (i = 0; i < itemCount; ++i) { totalCost += itemCosts[i]; } return totalCost; }
内容的提问来源于stack exchange,提问作者megat khairie

