c++ - 代码占用了我一半的输入

标签 c++ if-statement

我正在上编程课学习 C++。我们必须解决 if 和 else 语句问题。下面是我的代码,我试图找出它减半的原因。

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

   int age;
   double price;
   char category;
   double finalPrice;

   cin >> price;
   cin >> age;
   cin >> category;

if (age <= 0) {
   cout << "Wrong input";
   }
if (age > 0 && age <= 5) {
   if (category != 'A' || 'a') {
      finalPrice = price - (( price * 100)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }

else if(category == 'A' || 'a') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
}

if (age > 5 && age <= 12) {
   if (category != 'B' || 'b') {
      finalPrice = price - (( price * 50)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'B' || 'b') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }   
   }

if (age > 12 && age <= 26) {
   if (category != 'C' || 'c') {
      finalPrice = price - (( price * 60)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'C' || 'c') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }      
}

if (age > 26 && age <= 60) {
   if (category != 'D' || 'd') {
      finalPrice = price - (( price * 70)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'D' || 'd') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
}

if (age > 60) {
   if (category != 'E' || 'e') {
      finalPrice = price - (( price * 80)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'E' || 'e') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }      
}

return 0;
}

以上是我的学校作业代码。

当我输入值 14.56 25 C 我得到 5.8.2

的输出

但是我的预期输出应该是14.56

我只是在监督什么吗?我不明白它是怎么减半的。

谢谢!

最佳答案

(category != 'A' || 'a') 等 -

我怀疑你的意思是“类别不是‘A’或‘a’”;试试 ((category != 'A') && (category != 'a'))

提示:编译器正在评估两个语句 category != 'A' OR 'a'

因为 'a 是非零的,它会评估为 true 并打乱你的逻辑

此外,您可以通过采用大写的 category 并将其与“A”进行比较来简化此操作,因此只需要一次比较。

关于c++ - 代码占用了我一半的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52072465/

相关文章:

php - 如何使文件编辑成为有条件的?

java - "if"语句的问题

c++ - 由于错误 "cannot allocate an object of abstract type",无法覆盖父类中的虚方法

c++ - 像这种情况,boost vf2 可以处理 multimap 吗?

c++ - 准备废弃 std::iterator

java - if 语句满足后执行 else 语句

PHP 循环 x 次,使用 while 和 if

c++ - 为什么 C++ 继承机制不透明?

c++ - 为什么我的输入检查 if else 语句不起作用?

javascript - 简化具有重复结果的嵌套 if/else?