【问题标题】:Simple logic in C++. Not allowed to use an IF statementC++ 中的简单逻辑。不允许使用 IF 语句
【发布时间】:2014-02-13 04:29:26
【问题描述】:

所以我是编程和学习 C/C++ 的新手。任务是创建一个简单的程序,该程序将计算给定价格和物品数量的总和。我被难住的部分是我们不允许在创建程序时使用“if 或 switch 语句”。我们需要询问用户该项目是否应纳税,使用 1 表示是,使用 0 表示否。现在我有程序来计算并读出征税和非征税。任何帮助将不胜感激,我知道这是业余爱好者和最基本的编程。

#include <stdio.h>

#define TAX_RATE 0.065
int main() {

  int item_quantity, taxable;
  float item_price, total_with_tax, total_without_tax, a, b;

  // Read in the price of the item

  printf("What is the price of the item? (Should be less than $100)\n");
  scanf("%f<100", &item_price);

  // Read in the quantity of the item being purchased

  printf("How many of the item are you purchasing? (Should be less than 100) \n");
  scanf("%d<100", &item_quantity);

  // Read in if it is taxable or not

  printf("Is the item a taxed item (1 = yes, 0 = no)?\n");
  scanf("%d", &taxable);

  // Calculate total with tax

  a = item_quantity*item_price*(1 + TAX_RATE);

  // Calculate total without tax

  b = item_quantity*item_price;

  printf("Your total purchase will cost $%.2f\n", a);

  printf("Your total purchase will cost $%.2f\n", b);

  return 0;

}

【问题讨论】:

  • 你可以试试ternary operator。由于这是一个家庭作业,我将把实现留给你。

标签: c if-statement int double


【解决方案1】:

所以taxable01。现在看看这两行之间的相似之处:

a = item_quantity*item_price*(1 + TAX_RATE);
b = item_quantity*item_price;

您如何将这些单行设为使用 taxable 的值,以便在 taxable1 时执行第一行的操作,而在 taxable0 时执行第二行的操作?哪一点需要改变?你怎么能做到这一点?

既然是你的任务,我想这就足够了。


你似乎在挣扎。好的,请考虑以下与上述两行完全相同的行:

a = item_quantity*item_price*(1 + TAX_RATE);
b = item_quantity*item_price*(1);

它们之间有什么区别?什么东西消失了。使用基本数学运算符让某物消失的简单方法是什么?

答案与 C++ 的任何特殊内容无关。这只是数学!

【讨论】:

  • 所以在谷歌搜索如何使用三元运算符后,我想出了解决方案。
  • 总计 = (应税 == 1) ? item_quantityitem_price*( 1 + TAX_RATE) : item_quantityitem_price;
  • @user3050104 三元运算符比您需要的要复杂。它基本上是伪装的if,我敢肯定给你分配任务的人不希望你使用它。如果没有if 或三元运算符,这很容易解决。你可以用简单的算术来做。
  • 好的,但是如果没有 if 语句,我怎么能回忆起那些呢?
  • 啊,我想我明白了。将税率乘以应税
【解决方案2】:

在没有ifswitch 语句的情况下做出决策的最常见选项是&amp;&amp;(“和”运算符)、||(“或”运算符)、?:(三元运算符)、和*(乘法运算符)。

【讨论】:

    【解决方案3】:

    如果用户给你 0,你必须找到一种方法来否定 TAX_RATE。这是一个简单的数学运算,我们试图让你知道。

    【讨论】:

      【解决方案4】:

      你可以改变方程式:

      a = item_quantity*item_price*(1 + TAX_RATE);

      在等式中添加应税变量,使得当应税为 0 时,

      方程变为:

      a = item_quantity*item_price

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        相关资源
        最近更新 更多