c - 减少我的 if 语句中的代码量的问题
问题描述
我正在编写我的第一个 C 程序,没有一种方法可以弄清楚如何减小 if 语句的大小,出于某种原因,我认为它有点太长了。我尝试减少代码行数,使用它,但是当我更改某些内容时,我测试它时不会出现一些消息,例如购买成功或失败。我知道这是一个初学者的问题。你能帮我吗,如果可能的话,提供一些关于使用什么和研究以使其更简洁的提示?
if (input == 'A') {
calculation = budget - apple;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", apple);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else if (input == 'O') {
calculation = budget - orange;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", orange);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else if (input == 'P') {
calculation = budget - pear;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", pear);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
};
解决方案
创建一个临时变量(例如fruits
),并使用input
“无效项目”使用其他不可能的值来确定它应该设置为什么,例如:
if (input == 'A') {
fruits = apple;
} else if (input == 'O')
fruits = orange;
} else if (input == 'P') {
fruits = pear;
} else {
fruits = -1; // Invalid item
}
一旦完成,剩下的就可以变成:
if(fruits != -1) {
calculation = budget - fruit;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", fruits);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
} else {
fruits = -1; // Low budget or invalid item!
}
}
if(fruits == -1) {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
推荐阅读
- ios - VKDefault -Triangulator 无法完全三角化多边形 MapKit
- firebase - 无法将 Google-Apps-Script REST API 的 URL 参数正确地导入 firestsore
- ios - iOS 应用与 Watch App 与 Watch App 的区别
- tensorflow - 如何在 Keras 中使用自定义张量板直方图?
- java - 无法从 CursorWindow 读取第 305 行 col -1。确保在从光标访问数据之前正确初始化光标
- matlab - 更改 MNIST 数据集的标签。如何将数组写入 ubyte 格式?
- xml - Notepad++ 快捷方式映射器 编辑宏 XML
- r - 在另一列下添加一列并为其分配一个组
- amazon-web-services - AWS 认知 - 2FA
- python - 在重定向之前从 Flask 表单中获取多个输入值