为什么在给某个变量输入负数时,C会报错,而在另一个变量时却不会?
我在尝试编写一个货运公司程序,让用户输入包裹重量、路程长度,并询问是否需要更快的送达。程序应该收集所有输入,在最后向用户显示服务费,或者告诉他们出错了。
供参考,我是初学者,可能会有不少菜鸟级的错误,但这是我在Visual Studio中写的代码:
#include <stdio.h>
int main() {
int weight, length;
float fee;
char fast;
printf("Enter the package weight: ");
scanf_s("%d", &weight);
printf("Enter the road length (km): ");
scanf_s("%d", &length);
if (weight < 5 && weight >= 0) {
if (length <= 100) {
fee = 20;
}
else {
fee = 40;
}
}
else if (weight >= 5 && weight < 20) {
if (length <= 100) {
fee = 50;
}
else {
fee = 80;
}
}
else if (weight >= 20) {
if (length <= 100) {
fee = 100;
}
else {
fee = 150;
}
}
printf("Would you like a fast delivery? (Y/N): ");
scanf_s(" %c", &fast);
if (fast == 'Y' || fast == 'y') {
fee = fee + 20;
}
else {
fee = fee;
}
if (weight < 0 || length < 0) {
printf("You made a mistake!");
}
else {
printf("Total package fee: %.2f Credits", fee);
}
return 0;
}
运行时在任何场景下都没有问题,只有这个情况除外:
Enter the package weight: -4 // it could be any other negative number
Enter the road length (km): 5 // this could be any number, negative or positive or zero
Would you like a fast delivery? (Y/N): y // could be anything
最后按回车时,我得到一个错误,显示在第45行,并且说:
异常抛出
运行时检查失败#3 - 变量 'fee' 未初始化就被使用。
我到底做错了什么?我处于学习阶段,因此任何帮助/意见都将不胜感激。
解决方案
当你输入 "-4" 时,没有任何if-else条件会成立,因此 "fee" 永远不会被赋值。你可以在最开始就将它初始化为0,例如在最开始写成:float fee = 0;。
并向用户说明不接受负数。
把这一行移动到完成输入长度之后紧接着的位置。希望这对你有帮助。
if (weight < 0 || length < 0) {
printf("You made a mistake!");
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。