我是 C 语言编码的新手。我试图让下面的项目运行,但它说我的程序在我输入第三个输入后停止工作。我不确定我选择对 all 或 bool 值使用 while 循环是解决这个问题的正确选择。我几乎觉得应该在程序的某处添加一个 if/else 语句。
我已经获得了该项目的流程图,基本上是这样的:
Get input values for inv1-4
While code !=-1
if code is !=1 proceed with loop and get input values for amounts bought/sold
else print inv1-4
#include <stdio.h>
int main(void)
{
int inv1;
int inv2;
int inv3;
int inv4;
int amount_purchased;
int amount_sold;
printf("Please provide beginning inventory amounts in cases between 1 and 4.\n\n");
printf("Enter the number of inventory for Piels (ID number 1): ");
scanf("%d", &inv1);
printf("\nEnter the number of inventory for Coors (ID number 2): ");
scanf("%d", &inv2);
printf("\nEnter the number of inventory for Bud (ID number 3): ");
scanf("%d", &inv3);
printf("\nEnter the number of inventory for Iron City (ID number 4): ");
scanf("%d", &
inv4);
while (inv1 != -1 && inv2 != -1 && inv3 != -1 && inv4 != -1) {
printf("\nEnter the number of cases of Piels (ID 1) purchased and sold this week.\n");
printf("Amount purchased: \n");
scanf("%d", &amount_purchased);
printf("Amount sold: \n");
scanf("%d", &amount_sold);
inv1 = inv1 + amount_purchased - amount_sold;
printf("\nEnter the number of cases of Coors (ID 2) purchased and sold this week.\n");
printf("Amount purchased: \n");
scanf("%d", &amount_purchased);
printf("Amount sold: \n");
scanf("%d", &amount_sold);
inv2 = inv2 + amount_purchased - amount_sold;
printf("\nEnter the number of cases of Bud (ID 3)purchased and sold this week.\n");
printf("Amount purchased: \n");
scanf("%d", &amount_purchased);
printf("Amount sold: \n");
scanf("%d", &amount_sold);
inv3 = inv3 + amount_purchased - amount_sold;
printf("\nEnter the number of cases of Iron City (ID 4) purchased and sold this week.\n");
printf("Amount purchased: \n");
scanf("%d", &amount_purchased);
printf("Amount sold: \n");
scanf("%d", &amount_sold);
inv4 = inv4 + amount_purchased - amount_sold;
}
printf("Ending inventory is as follows.\n\n");
printf("Piels (ID Number 1): %d \n", inv1);
printf("Coors (ID Number 2): %d \n", inv2);
printf("Bud (ID Number 3): %d \n", inv3);
printf("Iron City (ID Number 4): %d \n", inv4);
return 0;
}
最佳答案
我猜是这个问题
while (inv1 || inv2 || inv3 || inv4 != -1)
是你写的不是你期望的。 (inv1 || inv2 || inv3 || inv4 != -1)
计算结果为真
inv1
不为 0,或 inv2
不为 0,或 inv3
不为0,或 inv4
不是-1。您可能想要的是,如果这些变量中的任何一个
为-1,循环必须结束。在这种情况下,正确的条件是:
while(inv2 != -1 && inv2 != -1 && inv3 != -1 && inv4 != -1)
{
...
}
请注意,在 bool 代数中 a && b
等同于 !a || !b
。和一个|| b
等同于 !a && !b
。
正如许多人在评论中所写的那样,您的 scanf
也是错误的。你必须
传递指向 int
的指针,而不是 int
。所以不是
scanf("%d", amount_sold);
应该是
scanf("%d", &amount_sold);
这适用于您所有的 scanf
调用,否则它是未定义的行为
未定义行为的结果是未定义的。
编辑
我刚刚注意到您在循环末尾有一个无条件的 break
。如果
你在第一次迭代中无论如何都要离开循环,你为什么要循环
首先?或者您是否忘记为
中断
?
关于C While 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098826/