C语言入门经典(第5版)2.16练习的答案!

2025-03-17 11:17:25
推荐回答(1个)
回答1:

/* Exercise 2.3  Calculating volume price of alternative products */

/* The only problem here is to devise a way to determine the price     */
/* for the product type. Here I used the product type value to do this. */
#include 

int main(void)
{
  double total_price = 0.0;                /* Total price      */
  int type = 0;                            /* Product type     */
  int quantity = 0;                        /* Quantity ordered */
  const double type1_price = 3.50;
  const double type2_price = 5.50;

  /* Get the product type */
  printf("Enter the type (1 or 2): ");
  scanf("%d", &type);

  /* Get the order quantity */
  printf("Enter the quantity: ");
  scanf("%d", &quantity);

  /* Calculate the total price */
  total_price = quantity*(type1_price + (type-1)*(type2_price-type1_price));

  /* Output the area */
  printf("The price for %d of type %d is $%.2f\n", quantity, type, total_price);
  return 0;
}
//////////////////////////////////////////////////////////////////////////////////
/* Exercise 2.4  Calculating average hourly pay rate */
#include 

int main(void)
{
  double pay = 0.0;                /* Weekly pay in dollars */
  double hours = 0.0;              /* hours worked          */
  int dollars = 0;                 /* Hourly rate - dollars */
  int cents = 0;                   /* ... and cents         */

  /* Get the Weekly pay */
  printf("Enter your weekly pay in dollars: ");
  scanf("%lf", &pay);

  /* Get the order quantity */
  printf("Enter the hours worked: ");
  scanf("%lf", &hours);

  /* Calculate the average hourly rate - dollars first */
  dollars = (int)(pay/hours);

  /* to get the cents we can subtract the dollars from the hourly rate           */
  /* and multiply by 100 to get cents. If we then add 0.5 and convert the result */
  /* back to an integer, it will be to the nearest cent.                         */
  cents = (int)(100.0*(pay/hours - dollars) +0.5);

  /* Output the average hourly rate */
  printf("Your average hourly pay rate is %d dollars and %d cents.\n", dollars, cents);
  return 0;
}