我正在做作业,并试图编写代码来回答这个问题:
编写一个计算货物总重量的程序。用户具有许多类型的框(编号从1到n)。对于每种盒子类型,程序都会询问用户重量和数量。然后程序计算并打印总货物重量。 在下面的输出示例中,用户具有三种框类型。对于框类型2,用户输入前哨-1到 表示输入已完成。您的程序应打印Type 1、2、3等,如 输出如下。
Enter weight (lbs) of Type 1 box: 4
Enter quantity: 2
Enter weight (lbs) of Type 2 box: -1
The total weight is 8 lbs.
当我运行此代码时,它将运行第一行以输入权重,但随后给我一个分段错误并说(核心已转储)。 -1是前哨,即使输入权重在while循环内,结果也相同。我究竟做错了什么?对不起,我是C的新手。
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", weight);
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
答案 0 :(得分:1)
这不是您使用scanf
scanf("%d", weight);
scanf("%d", quantity);
您应该传递变量的地址,而不是变量的值。
它看起来像这样:
scanf("%d", &weight);
scanf("%d", &quantity);
您的while循环取决于值weight
。 weight
的值永远不会在循环中更改,因此循环永远不会退出。
此行:
total_weight= total_weight + (quantity*weight);
使用从未初始化的total_weight
值。
您应该初始化变量。
#include <stdio.h>
int main()
{
int weight = 0; //weight of boxes
int quantity = 0; //number of boxes
int total_weight = 0; //total weight
int n = 1;
while(weight!=-1)
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight); // Update weight **inside** the loop
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
答案 1 :(得分:0)
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
问题处于条件状态,权重永远不会改变其值,因此条件始终为true,因此会无限循环。
修正此声明scanf("%d", &weight);
答案 2 :(得分:0)
您的问题是,您尝试为quantity
和weight
的指针分配一个值,相反,您需要放入&quantity
和&weight
,而您没有权重的另一个输入,您还应该使用do while代替while循环。看起来应该像这样
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
do
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight);
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}while (weight != -1);
printf("The total weight is %0.2d", total_weight);
return 0;
}