C语言,如果语句混乱

时间:2020-05-21 04:27:21

标签: c if-statement

更新:代码现在可以完美运行

关闭UPDATE。

您需要考虑两种不同的情况:购买偶数个牛奶纸箱和购买奇数个牛奶纸箱。您如何确定数字是偶数还是奇数?

这是我到目前为止所写的内容,请给我一些指导。我希望我有道理。


    if (milk_boxes % 2 == 0)


    total = milk_boxes * milk_price / 2;
    else


    total = (milk_boxes - 1) * milk_price / 2 + milk_price;







2 个答案:

答案 0 :(得分:1)

我可以在您的代码中看到一个问题。如果容器为奇数,则您正在计算并显示价格。但是我认为您忘了计算容器的价格(即使它们的数量是偶数),您只是在打印变量OJ_containers的值。您还必须计算并显示它。

在寻找准则时,建议您遵循Microsoft的编码准则:

The Microsoft's coding guidelines

我知道它适用于c#,但是您仍然可以将这些准则用于其他编程语言。其他编程语言有很多共同点。就像变量,函数的概念一样,在C#中,它们将其称为方法。希望你喜欢。随着您的进步,您会知道有很多编程方法,但不要混淆,只需遵循一次标准,我希望您从一开始就这样做,它将帮助您成为一名优秀的程序员。

尝试此代码:

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

int main() {

    double OJ_price;
    int OJ_containers;

    printf("What is the cost of one container of OJ in dollars?\n");
    scanf("%lf", &OJ_price);

    printf("How many containers are you buying?\n");
    scanf("%d", &OJ_containers);

    if(OJ_containers % 2 == 0)
        printf("The total cost is %1f\n", (OJ_containers*OJ_price)/2);
    else
        printf("The total cost is $ %.2f\n",                      
((OJ_containers/2)*OJ_price)+OJ_price);

return 0;

}

答案 1 :(得分:0)

在“奇数”情况下,BOGO报价不会被2除。下面的示例-我将printf分开来进行了一些澄清。

double total;

if (OJ_containers % 2 == 0)
    // even means simply divide full price by two
    total = OJ_containers * OJ_price / 2;
else
    // odd means half price for the pairs, plus one more bottle at full price
    total = (OJ_containers - 1) * OJ_price / 2 + OJ_price;

printf("The total cost is %f\n", total);
相关问题