为什么我的答案每次都不同?

时间:2017-03-29 11:10:11

标签: c

我一直在编写一个程序,您可以将程序中的买方公司ID和产品ID提供给它,并根据公司的独家折扣和其他一些折扣给您提供价格。

然而,每次我测试它(使用相同的输入),我得到一个完全不同的答案,通常比我的预期答案大几百倍。我还是C和编程的新手,所以我在这个程序中使用的很多方法我以前从未做过。

#include <stdio.h>

char compID[30];
double discount;
char prodID[30];
int prodAmount = 0;
double productPrice;
double tax;
double totalprice = 0;



int main() {

    char cont[2];

    printf("What is your company ID? ");
    scanf("%s", compID);

    if (strcmp(compID, "BFSC") == 0) {

        discount = 1;
        tax = 1.1;

    }

    do {

        int itemPrice;

        printf("What is the idea of the product you'd like to purchase? ");
        scanf("%s", prodID);

        if (strcmp(prodID, "FENG") == 0) {

            productPrice = 12124.50;

        }

        printf("How many? ");
        scanf("%d", &prodAmount);


        printf("Do you want to purchase another item? (y/n) ");
        scanf("%s", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = prodAmount*productPrice*tax*discount;
    printf("%d", &totalprice);


}

如果我将BFSC作为公司ID而FENG作为产品ID,我得到的答案是100万加,而不是13336.95。

1 个答案:

答案 0 :(得分:2)

我已经检查了你的代码只是格式说明错误,你有一些类型问题,你正在计算总价格,但打印地址printf(“%d”,&amp; totalprice);

和totalprice = prodAmount(int type)* productPrice(double)* tax(double)* discount(double)

如果您不进行任何类型转换,那么它总是会将一些垃圾数据作为输出或整数值。请尝试以下代码,这可能会对您有所帮助

#include <stdio.h>
char compID[30];
double discount;
char prodID[30];
float prodAmount = 0;
float productPrice;
float tax;
float totalprice;
int main() {

    char cont = 0;

    printf("What is your company ID? ");
    scanf("%s",compID);

    if (strcmp(compID, "BFSC") == 0) {

            discount = 1;
            tax = 1.1;

    }

    do {

            int itemPrice;

            printf("What is the idea of the product you'd like to purchase? ");
            scanf("%s", prodID);

            if (strcmp(prodID, "FENG") == 0) {

                    productPrice = 12124.50;

            }

            printf("How many? ");
            scanf("%f",&prodAmount);


            printf("Do you want to purchase another item? (y/n) ");
            scanf(" %c", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = ((prodAmount * productPrice) * tax )* discount;

    printf("%0.02f\n", totalprice);


}