C语言main函数调用自定义函数时程序卡住无报错如何解决
问题原因
- 死循环是程序无响应的直接原因:
discount_price函数中的while循环,循环体内没有修改i的值,只要满足memberCard == 'Y'的条件,i永远为0,永远符合i <= quantity的判断,循环永远不会退出。 - 变量未初始化:
before_discount_price里的局部变量total没有赋初值就直接累加,会得到垃圾值;discount_price里的discount、totalprice也没有初始化,计算结果会异常。 - 逻辑错误:
before_discount_price里的return写在while循环内部,第一次循环执行完就直接返回,无论购买多少张票都只会计算1张的价格;main函数中调用discount_price时传的第二个参数是未初始化的total,应该传入之前计算得到的price。 - 输入输出错误:main函数里打印
total时多加了&,相当于打印变量的内存地址而不是值,输出会异常;fflush(stdin)属于未定义行为,不同编译器表现不一致;已经被废弃的gets函数存在缓冲区溢出风险。 - 函数返回逻辑不严谨:
before_discount_price声明返回float类型,但部分分支存在无返回值的问题,会引发不可预期的错误。
修复后可运行代码
#include <stdio.h> float before_discount_price(int, int, char); float discount_price(float, char); void displayinfo(); int main() { char name[20], customerID[20], type, memberCard; int quantity, age; float price, total; printf("Enter Your Name: "); // 替换gets为fgets避免缓冲区溢出 fgets(name, 20, stdin); printf("Enter Your ID: "); scanf("%s", customerID); printf("Your Age: "); scanf("%d", &age); // 替换fflush(stdin),清理输入缓冲区残留的换行符 while(getchar() != '\n'); printf("Choose your Activities: (A for Waterpark, B for Safari Night): "); scanf("%c", &type); printf("How many tickets you want to buy: "); scanf("%d", &quantity); while(getchar() != '\n'); printf("Do you have a member card?: (Y for Yes, N for No):"); scanf("%c", &memberCard); price = before_discount_price(quantity, age, type); total = discount_price(price, memberCard); // 去掉&,正确打印变量值 printf("Total to pay: %.2f\n", total); return 0; } float before_discount_price(int quantity, int age, char type) { // 初始化total为0 float total = 0; int i = 1; int single_price; // 单张票价无需在循环内重复判断,放到循环外提升效率 if (type == 'A') { single_price = age >= 18 ? 30 : 15; } else if (type == 'B') { single_price = age >= 18 ? 25 : 15; } else { // 非法输入默认按0计算,可自行补充错误处理逻辑 single_price = 0; } while (i <= quantity) { total += single_price; i++; } // return放到循环外部,计算完所有票数再返回 return total; } float discount_price(float total, char memberCard) { float discount = 0; if (memberCard == 'Y') { discount = total * 0.3; } // 删除无用的循环逻辑 return total - discount; } void displayinfo() { printf("Hi"); }
内容的提问来源于stack exchange,提问作者Alpha Chong
相关产品推荐
相关产品推荐

