[英]C++ program sometimes giving wrong answer
我有这个程序,它应该根据用户的输入给我最小的商品原价。 有一些条件,例如口罩的数量超过9个,价格折扣10%,超过30个折扣15%,超过50个折扣20%。结果应该在这里给出答案是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
int mprice; //price input
int mquantity; //quantity input
int n; //first input
int fee = 2000; //const fee
float finalprice;
float maskCalc(int price, int quantity) {
float holder = (float)(price - fee) / (float)(quantity);
if (quantity > 0) {
finalprice = holder;
}
//if between 10 and 30
else if (quantity > 9) {
finalprice = holder / 0.9;
}
//between 30 and 49
else if (quantity > 30) {
finalprice = holder / 0.85;
}
//more than 50
else if (quantity > 49) {
finalprice = holder / 0.8;
}
//less than ten
else {
finalprice = holder;
}
return finalprice;
}
int main()
{
cin >> n;
float arr[n];
// Input oruulah loop
for (int i = 0; i < n; i++) {
cin >> mprice >> mquantity;
x = maskCalc(mprice, mquantity);
arr[i] = x;
}
for (int i = 1; i < n; i++) {
if (arr[0] > arr[i]) {
arr[0] = arr[i];
}
}
printf("%.2f", arr[0]);
return 0;
}
我输入 3 5000 3 7000 10 3000 1 答案是 555.56,这是正确的,但是当我输入 3 2500 1 7000 10 3000 1 之类的东西时,它给了我 0.00,而我期望这会给我 500.00。 任何帮助将不胜感激。
您需要首先在 if-else 开关中检查最高数量,否则您总是会陷入默认 (<10) 的情况。
//more than 50
if (quantity >= 50) {
finalprice = holder / 0.8;
}
//between 30 and 49
else if (quantity >= 30) {
finalprice = holder / 0.85;
}
//if between 10 and 30
else if (quantity >= 10) {
finalprice = holder / 0.9;
}
//less than ten
else {
finalprice = holder;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.