【问题标题】:Taking in a list of prices, reducing and summing it all up获取价格清单,减少并总结所有价格
【发布时间】:2020-11-19 11:52:17
【问题描述】:

所以我陷入了一个while循环。

我不能使用数组。

我必须接受一个数字列表(浮点数/双精度数),(假设第一个数字是正数并且代表商店商品价格)如果下一个数字是负数,我必须从总和中减去旧价格并添加新价格是旧价格减去百分比(负数),然后将其存储在总和中。

我在尝试逻辑推理时有点迷路了 将不胜感激。

我正在使用 C。

这是我目前得到的:

int main() {
  float factor = 0, avgPrice = 0, sum = 0, productPrice = 0, temp = 0;
  int productCount = 0;
  printf("Enter a positive factor: ");
  scanf("%f", &factor);
  while (factor < 0.0001) {
    printf("Invalid factor. Please enter again: ");
    scanf("%f", &factor);
  }
  printf("Enter the list of products in the shopping cart: ");
  scanf("%f", &productPrice);
  if (productPrice <= 0) {
    printf("Error! Invalid input.");
    return 1;
  }
  sum = productPrice;
  productCount++;
  float sumCopy = 0;
  float priceDeduction = 0;
  temp = productPrice;
  while (scanf("%f", &productPrice) != 0) {
    if (productPrice == 0) {
      break;
    }
    sumCopy = sum;

    if (productPrice < 0) {
      sum -= temp;
      priceDeduction = (temp * productPrice) / 100;
      temp -= priceDeduction;
      sum += temp;
    }
    if (productPrice > 0) {
      productCount++;
      sum += productPrice;
      temp = productPrice;
    }
  }
  printf("Final payment: %.2f", sum);
}

【问题讨论】:

  • 首先编辑您的帖子以修复缩进。
  • 如果你被困在这个循环中while(scanf("%f",&amp;productPrice)!=0),请解释你在这个条件背后的想法。参考返回值说明en.cppreference.com/w/c/io/fscanf
  • 使用了什么输入?
  • 嘿,如果问题的解决方案有用,请指出它,或者如果您找到了问题的答案,请提及它。 Stackoverflow 就像一本百科全书。许多人使用它,其他人可能也有同样的问题。

标签: c loops


【解决方案1】:

如果我正确理解了您的问题,那么您想找到总价。我不明白你为什么在 while 中写了一个 Scanf 语句,什么是因素。它没有在其他任何地方使用

我正在为上面的陈述写一个解决方案。

#include <stdio.h>
#include <math.h>
int main() {
   char ch = 'N';
   int p, sp;
   int sum = 0;
   do
   {
      printf("Enter the product price: ");
      scanf("%d", &p);
      if (p > 0)
      {
         //temp = productPrice;
         sum += p;
      }
      else
      {
         printf("Please enter a valid first product price.\n");
         break;
      }
      printf("Enter the second product price: ");
      scanf("%d", &sp);
      if (sp > 0)
      {
         sum += sp;
      }
      else if (sp < 0)
      {
         sum += sp;
     
      }
      printf("\nAre you done with the list of products to buy? enter Y or N ");
      scanf(" %c", &ch);
   }while(ch == 'N');
   printf("The final payment is %d ", sum);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多