如何在C++顺序IF语句中实现特定计费计算?代码问题求助
修正后的代码
#include <stdio.h> int main() { char ticketType; int totalBill, studAmount; const int PRICE_R = 6500, PRICE_G = 7500; // 用常量定义票价,提升可读性 printf("Enter your ticket type (R/G): "); scanf(" %c", &ticketType); // 加空格跳过输入缓冲区的空白字符(如换行) printf("Enter amount of students: "); scanf("%d", &studAmount); // 顺序IF判断票种并计算费用 if(ticketType == 'R') { totalBill = studAmount * PRICE_R; // 使用赋值运算符=,而非相等判断== printf("\nYour ticket type is R and your total bill is: %d\n", totalBill); // 格式化参数与占位符匹配 } if(ticketType == 'G') { totalBill = studAmount * PRICE_G; printf("\nYour ticket type is G and your total bill is: %d\n", totalBill); } printf("The amount of students attending are: %d\n", studAmount); return 0; }
原代码核心错误及修正说明
- 票种判断逻辑错误:原代码用值为6500的int变量
ticketType_R和用户输入的字符ticketType比较,而用户输入的'R'ASCII码为82,两者永远不相等。修正为直接和字符常量'R'/'G'比较。 - 赋值运算符误用:
totalBill==studAmount*6500是相等判断操作,不会给totalBill赋值,必须改为赋值运算符=。 - printf参数不匹配:原printf语句仅一个
%d占位符,却传入两个参数,导致输出混乱。修正后仅传入计算好的totalBill即可。 - 输入缓冲区问题:首次
scanf("%c")可能读取到用户输入后的换行符,导致票种读取错误。在%c前加空格" %c"可自动跳过空白字符。 - 变量命名优化:将票价定义为
const常量,避免误修改,同时提升代码可读性。
内容的提问来源于stack exchange,提问作者Qwesi Brown
相关产品推荐
相关产品推荐

