-4

您的程序应该要求用户输入一箱果汁的价格以及购买的纸箱数量。请注意,由于果汁是一种普通的杂货,因此不收取销售税。

然后,确定在 BOGO 报价下购买橙汁的最终成本。

int main() {
  //variables
  int carton, total;
  float cost;

  printf("What is the cost of one container of OJ in dollars?\n");
  scanf("%4f", &cost);
  printf("How many containers are you buying?\n");
  scanf("%d", &carton);
  if (carton % 2 == 0) {
    total = (carton / 2) * cost;
  } else {
    total = (carton % 2) * cost + (carton - 1 / 2) * cost;
  }

  //output
  printf("The total cost is $%d", total);

  return 0;

}
4

2 回答 2

0

首先,如果您希望 yourtotal是一个浮点数而不是“四舍五入”,因为您将其转换为 a int,那么您必须将其声明为 a float。此外,您在代码中还有一些计算,因为您使用的是整数,所以您得到的答案是您不期望的。(例如carton - 1/2)。我强烈建议您将所有 3 个变量更改为浮点数。

其次,在您的最后一行中,您写道:

printf("The total cost is $%d", total);
  • %d用于整数
  • %f用于花车

当你做%d浮动时,你正在铸造它。这意味着它与做相同(int)total,因为整数只是整数,所以你total也将是一个整数。

长话短说..如果您不想total“四舍五入”,请使用:

int main() {
//variables
float carton, cost, total;


printf("What is the cost of one container of OJ in dollars?\n");
scanf("%4f", &cost);
printf("How many containers are you buying?\n");
scanf("%f", &carton);
if (carton % 2 == 0) {
    total = (carton/ 2)*cost;
}
else {
    total = (carton % 2)*cost + (carton - 1/ 2)*cost;
}

//output
printf("The total cost is $%f", total);

return 0;
于 2020-09-22T05:21:24.987 回答
0

您只需在分割纸箱之前将其键入浮动即可。通过这种方式,您还可以使用模数(%)运算符,因为它实际上是一个整数,您还可以通过将其类型转换为浮点数将其除以 2

于 2020-09-22T04:22:23.313 回答