C语言自定义函数中if条件失效问题求助
问题原因及修复方案
核心问题1:输入缓冲区残留换行符导致字符读取错误
main函数中,用scanf("%d", &typeOfRoom)读取整数后,用户输入的换行符会留在输入缓冲区。后续执行scanf("%c%*c", &a_basis)时,第一个%c会直接读取这个换行符,导致a_basis的值不是预期的F/f或H/h,自然触发不了calculate函数里的条件分支。
修复方法:
在读取字符的scanf格式前加空格,自动跳过前面的空白字符(包括换行):
scanf(" %c%*c", &a_basis);
核心问题2:calculate函数中typeOfRoom==3分支逻辑错误
第三个分支的else if重复判断了F/f,应该改为判断H/h:
else if (typeOfRoom==3){ if(a_basis=='F' || a_basis=='f'){ total = 9000.00; } else if(a_basis=='H' || a_basis=='h'){ // 修正此处的判断条件 total = 7250.00; } }
额外问题:typeOfRoom未初始化就进入循环
main函数里的typeOfRoom没有初始值,直接进入while(typeOfRoom != -1)会触发未定义行为,可能直接跳过循环。需要初始化它为非-1的值:
int typeOfRoom = 0, no_days;
修复后的完整代码
#include<stdio.h> double calculate(int typeOfRoom, char a_basis){ double total = 0.0; // 初始化total,避免未赋值返回垃圾值 if (typeOfRoom==1){ if(a_basis=='F' || a_basis=='f'){ total = 25555.00; } else if(a_basis=='H' || a_basis=='h'){ total = 17250.00; } } else if (typeOfRoom==2){ if(a_basis=='H' || a_basis=='h'){ total = 17500.00; } else if(a_basis=='F' || a_basis=='f'){ total = 12250.00; } } else if (typeOfRoom==3){ if(a_basis=='F' || a_basis=='f'){ total = 9000.00; } else if(a_basis=='H' || a_basis=='h'){ total = 7250.00; } } return total; } int main(void){ int typeOfRoom = 0, no_days; // 初始化typeOfRoom char crd_type; char a_basis; double total; while(typeOfRoom != -1){ printf("Enter Room type :"); scanf("%d", &typeOfRoom); if(typeOfRoom == -1) break; // 输入-1直接退出,避免后续无效读取 printf("Enter Accommodation Basis (F/H) :"); scanf(" %c%*c", &a_basis); // 跳过空白字符读取目标字符 total = calculate(typeOfRoom, a_basis); printf("Total: %.2lf\n", total); // 格式化输出更清晰 } return 0; }
内容的提问来源于stack exchange,提问作者kaweesha marasinghe
相关产品推荐
相关产品推荐

