C语言使用函数计算水费时输出异常、用户类型判断错误求助
问题排查结果
你代码存在以下几处明确错误:
1. 用水量参数传递错误
main函数中你从文件读取的用水量存储在cf变量中,但调用water_billcalculation函数时传的是未赋值的water_use变量,该变量值始终为0,直接导致所有水费计算结果完全错误。
2. 用户类型大小写不匹配
你在函数判断逻辑中只匹配了大写的G/B/R,但文件里第一个用户类型是小写的g,匹配失败直接触发错误提示。
3. fscanf读取格式错误
%c格式化符会读取换行、空格等所有空白字符,你读完每一行的数值后,下一次读取会把行尾的换行符当成user_type读取,直接触发错误提示,这就是你表头后直接输出错误的核心原因。
4. 输出格式不符合要求
你用%lf输出金额默认保留6位小数,和预期的2位小数不符。
修复后的代码示例
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <ctype.h> // 引入字符处理库做大小写转换 double water_billcalculation(char user_type, double water_use); int main(void) { FILE* water = fopen("water_usage.txt", "r"); if (water == NULL) { perror("打开文件失败"); return 1; } char user_type; int cf; printf("Type Water usage Cost including tax($)\n"); // 格式串前加空格跳过所有空白字符,避免读入换行 while (fscanf(water, " %c%d", &user_type, &cf) != EOF) { double res = water_billcalculation(user_type, cf); if (res >= 0) { // 合法用户类型才输出账单 printf("%-6c%-17d%.2f\n", user_type, cf, res); } } fclose(water); return 0; } double water_billcalculation(char user_type, double water_use) { double bft, at; // 统一转大写判断,兼容大小写输入 char type = toupper(user_type); if (type == 'G') { bft = (water_use * 0.035) + 3.75; at = bft * 1.087; } else if (type == 'B') { bft = (water_use * .0553) + 17.25; at = bft * 1.087; } else if (type == 'R') { if (water_use <= 400) { bft = (water_use * .04) + 13.5; } else if (water_use <= 700) { bft = (water_use * .062) + 13.5; } else { bft = (water_use * .12) + 13.5; } at = bft * 1.087; } else { printf("Wrong user type\n"); return -1; // 非法类型返回负值标识 } return at; }
内容的提问来源于stack exchange,提问作者ahsokatano
相关产品推荐
相关产品推荐

