[英]C language, if statement confusion
更新:代碼現在運行完美
關閉更新。
您需要考慮兩種不同的情況:購買偶數個牛奶盒和購買奇數個牛奶盒。 如何判斷一個數是偶數還是奇數?
這是我到目前為止所寫的內容,我需要一些指導。 我希望我說得通。
if (milk_boxes % 2 == 0)
total = milk_boxes * milk_price / 2;
else
total = (milk_boxes - 1) * milk_price / 2 + milk_price;
我可以在您的代碼中看到一個問題。 如果容器為奇數,您正在計算並顯示價格。 但我認為如果容器的數量是偶數,你會忘記計算容器的價格,你只是在打印變量 OJ_containers 的值。 您還必須計算和顯示它。
當您正在尋找指南時,我建議您應該遵循 Microsoft 的編碼指南:
我知道它適用於 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;
}
在您的“奇數”案例中,您不會將 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.