2014-01-22 59 views
0

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

#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; 

} 
+0

您可以尝试[三元操作符(HTTP: //en.wikipedia.org/wiki/Ternary_operation)。由于这是一项家庭作业,我将使用它完成实施。 – marko

回答

7

所以taxable或者是01。现在看这两条线之间的相似性:

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++的特殊之处无关。这只是数学!

+0

所以谷歌搜索后如何使用三元运算符我想出了解决方案。 – mikeboyd941

+0

total =(应纳税== 1)? item_quantity * item_price *(1 + TAX_RATE):item_quantity * item_price; – mikeboyd941

+1

@ user3050104三元运算符比您需要的更复杂。它基本上是一个伪装的“if”,我相信给你任务的人不希望你使用它。如果没有“if”或三元运算符,这很容易解决。你可以用简单的算术来做到这一点。 –

0

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

1

对于没有ifswitch声明决策最常用的选项是&&(“和”运营商),||(“或”运算符),?:(三元运算符),和*(乘法运算符)。

0

U可以更改等式:

一个= item_quantity * ITEM_PRICE *(1 + TAX_RATE);

公式中以这样的方式添加应税变量,当应纳税为0,

公式变为:

A = item_quantity * ITEM_PRICE