编写一个计算货物总重量的程序. C.

  • 本文关键字:总重量 程序 计算 一个 c
  • 更新时间 :
  • 英文 :


>我正在尝试编写一个计算货物总重量的程序。用户将输入框数和 他们拥有的每种类型的箱子的箱子重量。我的代码在提示用户输入权重时不断重复"输入框数"两次。我该如何解决这个问题?这是我的代码:

#include<stdio.h>
int main()
{
int x,y,total=0; // variables
{
while(!(x==-1 || y==-1)){
printf("Enter the number of boxes:");
scanf("%d",&x);
printf("Enter the weight(lbs):");
scanf("&d",&y);
total+=(x*y);
}
printf("n");
}
if (x==-1 || y==-1) {  // when the user inputs -1, the next 
line will execute
printf("The total weight is:%d",total);
}
printf("n");
system("PAUSE");
return 0;
}

我根据其他人写给你的评论编辑了你的代码:

#include <stdio.h>
int main()
{
int x = 0,y = 0,total=0; // variables

while(!(x==-1 || y==-1)){
printf("Enter the number of boxes:");
scanf("%d",&x);
printf("Enter the weight(lbs):");
scanf("%d",&y);
total+=(x*y);
}
printf("n");

if (x==-1 || y==-1) 
{  // when the user inputs -1, the next  line will execute
printf("The total weight is:%d",total);
}
printf("n");
return 0;
}

我所做的只是把它写得更简单、更漂亮

祝你的家庭作业好运

这里有一些固定的代码,尽管你需要这些新的标头才能让它工作

#include<stdio.h>
#include <string.h>
#include <stdlib.h>

所以我认为您遇到的问题是您的输入缓冲区跳过了第二个值。 为了解决这个问题,我改用了 FGETS,因为它更容易机智地工作。

char input[3];
int x = NULL;
int y = NULL;
int total = 0; // variables
while (x == NULL || y == NULL) 
{
printf("Enter the number of boxes:");
fgets(input, 3, stdin);
input[strlen(input) - 1] = 0;
x = atoi(input);
printf("Enter the weight(lbs):");
fgets(input, 3, stdin);
input[strlen(input) - 1] = 0;
y = atoi(input);
total += (x*y);
}

输入数组中的 3 需要等于您希望接受的字符数 + 2(以考虑/N/0 终止)

最新更新