-4

所以这是我的代码。出于某种原因,它总是说四分之一的数量是 4。我做错了什么?

#include <stdio.h>

#define QUARTER 25      // Define the constant cent values of the quarters, dimes, nickels, and pennies.
#define DIME    10
#define NICKEL  5
#define PENNY   1

int main( void ){

    int priceOfitem;  // Initialize the variable that will be the price.
    printf("Enter the price of an item less than one dollar (in cents) (eg: 57) : ");
    scanf("%lg", &priceOfitem);

    if(priceOfitem >= 100){
    printf("The price must be less than one dollar. \nProgramming exiting.");
    return 0;
    }



    int changeAmount = 100 - priceOfitem; /* Create the variable that is the amount of change needed.
                                           * This variable will be modified later on.
                                           */

    int amountOfQuarters = ((changeAmount - (changeAmount % QUARTER)) / QUARTER); // Utilizing the modulus operator to determine the amount of quarters.

    printf("\n\nThe Amount of Quarters Needed in the Change is: %d", amountOfQuarters);

    changeAmount = changeAmount - (amountOfQuarters * QUARTER); // Modifying the change amount


    int amountOfDimes = ((changeAmount - (changeAmount % DIME)) / DIME); // Utilizing the modulus operator to determine the amount of dimes.

    printf("\n\nThe Amount of Dimes Needed in the Change is: %d", amountOfDimes);

    changeAmount = changeAmount - (amountOfDimes * DIME); // Modifying the change amount


    int amountOfNickels = ((changeAmount - (changeAmount % NICKEL)) / NICKEL); // Utilizing the modulus operator to determine the amount of nickels.

    printf("\n\nThe Amount of Nickels Needed in the Change is: %d", amountOfNickels);

    changeAmount = changeAmount - (amountOfNickels * NICKEL); // Modifying the change amount


    int amountOfPennies = changeAmount; // Since the changeAmount can now be expressed with pennies only, set the amountOfPennies variable as such.

    printf("\n\nThe Amount of Pennies Needed in the Change is: %d", amountOfPennies);

    return 0;
}
4

2 回答 2

3

这里:

int priceOfitem;  // Initialize the variable that will be the price.
printf("Enter the price of an item less than one dollar (in cents) (eg: 57) : ");
scanf("%lg", &priceOfitem);

您需要传递"%d"给 scanf 以进行整数输入:

scanf("%d", &priceOfitem);

你也不需要这个减法:

int changeAmount = priceOfitem; //int changeAmount = 100 - priceOfitem

编译时始终使用-Wall -Werror(或您选择的编译器的类似标志)。

于 2013-01-18T23:22:32.580 回答
2

这不是您问题的真正答案,但是...

通常我们通过使用整数运算来计算四分之一的数量(以及类似的东西),这会丢弃任何小数部分。

 int amountOfQuarters = changeAmount / QUARTER;

所以,如果 changeAmount 是 57,我们使用整数运算除以 25,我们得到 2。

于 2013-01-18T23:26:48.003 回答