【发布时间】: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",&productPrice)!=0),请解释你在这个条件背后的想法。参考返回值说明en.cppreference.com/w/c/io/fscanf -
使用了什么输入?
-
嘿,如果问题的解决方案有用,请指出它,或者如果您找到了问题的答案,请提及它。 Stackoverflow 就像一本百科全书。许多人使用它,其他人可能也有同样的问题。