我怎样才能改变我的等式?

时间:2014-01-15 22:12:42

标签: c equation

我需要让用户输入1或0表示是否需要纳税。有人可以提供帮助,因为当用户输入0时它会输出0。这是我的代码。

#include<stdlib.h>
#include <stdio.h>

#define TAX_RATE 0.065

int main() {
  int item_value;
  int total_items;
  double total_cost;
  double is_taxable;

  printf("What is the cost of the item to be purchased (in dollars)?\n");
  scanf("%d", &item_value);

  printf("How many of the items are you purchasing?\n");
  scanf("%d", &total_items);

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

  total_cost =(TAX_RATE+is_taxable)*(item_value*total_items); 

  printf("Your total cost is %.2lf.\n", total_cost);

  system("Pause");
  return 0;
}

2 个答案:

答案 0 :(得分:2)

保持代码简单:

int is_taxable;
...
scanf("%d", &is_taxable);
...

if (is_taxable)
  total_cost = (1 + TAX_RATE) * (item_value * total_items);
else
  total_cost = item_value*total_items;

编辑我不知道你不能使用 if (为什么?)。所需的更改只是(删除if / else)

total_cost = (1 + TAX_RATE * is_taxable) * (item_value * total_items);

答案 1 :(得分:2)

不是像CapelliC所建议的那样引入一个新的变量“is_taxable”,你也可以采用以下方式。

total_cost =( 1 + TAX_RATE*is_taxable)*(item_value*total_items);

示例输出(含税)

What is the cost of the item to be purchased (in dollars)?
10
How many of the items are you purchasing?
2
Is the item taxed (1 = yes, 0 = no)?
1
Your total cost is 21.30.

示例输出(不含税)

What is the cost of the item to be purchased (in dollars)?
10
How many of the items are you purchasing?
2
Is the item taxed (1 = yes, 0 = no)?
0
Your total cost is 20.00.

要添加更多建议,最好将“item_value”的类型声明为double,以便用户可以输入10.25这样的输入。否则你会得到错误的结果。

示例输出(当输入10.25作为价格时)

#./a.out
What is the cost of the item to be purchased (in dollars)?
10.25
How many of the items are you purchasing?
Is the item taxed (1 = yes, 0 = no)?
Your total cost is 332994.64.