首页 > 解决方案 > 我该如何解决这个问题并调试它,因为我已经匹配了它

问题描述

.cpp(27): 错误 C2181: 非法 else 不匹配 if

cpp(37): 错误 C2181: 非法 else 不匹配 if

你好,如何解决这个问题我想建立一个关于折扣和订单总成本的程序

下面是代码..它说的问题,但我不能纠正它谢谢

#include < iostream >
using namespace std;
#define retailPrice 20

int main() {
  float quantity, discount;
  float totalCost;

  cout << "Welcome to GLAMOUR bookstore,Enjoy our cool promotion.\n";
  cout << "Please enter the quantity of packages you have purchased:";
  cin >> quantity;
  {
    if (quantity < 0)
      cout << "Sorry,quantity cannot be negative\n";

    else if (0 <= quantity && quantity < 10)
      discount = '0';
    totalCost = quantity * retailPrice;
  }

  {
    if (10 <= quantity && quantity <= 19) discount = '20';
    totalCost = quantity * retailPrice * 0.8f;

    else if (20 <= quantity && quantity <= 49) discount = '30';
    totalCost = quantity * retailPrice * 0.7f;
  }

  {
    if (50 <= quantity && quantity <= 99) discount = '40';
    totalCost = quantity * retailPrice * 0.6f;

    else if (quantity >= 100) discount = '50';
    totalCost = quantity * retailPrice * 0.5f;
  }

  cout << "Total cost of purchase = RM" << totalCost << ".\n";
  cout << "discount =" << discount << "%\n";

  return 0;
}

标签: c++if-statement

解决方案


这些错误是由括号错位引起的。检查此代码,我从中删除了错误:

#include <iostream>
using namespace std;
#define retailPrice 20

int main()
{
float quantity,discount;
float totalCost;

cout << "Welcome to GLAMOUR bookstore,Enjoy our cool promotion.\n";
cout << "Please enter the quantity of packages you have purchased:";
cin >> quantity;

if (quantity<0){
    cout << "Sorry,quantity cannot be negative\n";
}
else if (0<=quantity && quantity<10){
    discount = '0';
    totalCost = quantity * retailPrice;
}

if   (10<=quantity && quantity<=19){
    discount = '20';
    totalCost = quantity * retailPrice*0.8f;
}
else if  (20<=quantity && quantity<=49){
    discount = '30';
    totalCost = quantity * retailPrice*0.7f;
}

if (50<=quantity && quantity<=99){
    discount = '40';
    totalCost = quantity * retailPrice*0.6f;
}
else if (quantity>=100){
    discount = '50';
totalCost = quantity * retailPrice*0.5f;
}
    cout << "Total cost of purchase = RM" << totalCost << ".\n";
    cout << "discount =" << discount << "%\n";
    return 0;
   }

推荐阅读