2015-02-07 364 views
0

我想什麼就會在躲不過前言本我非常新的節目,並有很多值得學習。所以我有一個問題,我的嵌套if else語句被忽略。第二個和第三個「printf」語句是整數,但轉換爲小數,因爲它們是適用於大中型訂單價格的百分比折扣。我正在使用while循環來測試3個條件,如果它們全部滿足,則打印該消息,但是如果它們不符合,我已經做了3條if和if條件語句來測試哪些條件未被滿足。然而,我錯過了一些東西,因爲它們沒有被準確地打印出來。基礎小部件的成本不應高於基本價格,醫藥價格或者大價格,因爲這會使小部件虧本銷售。我不確定我做錯了什麼,除了我那些太類似的混淆名字。如果else語句,while循環破碎

#include <math.h> 
#include <stdio.h> 
#define widget_cost 0.40 

int main(){ 


float sellprice; 
int discount_med; 
float discount_med_price; 
float med_price; 
float large_price; 
int discount_large; 
float discount_large_price; 



    printf("How much are you selling each widget for\n"); 
     scanf("%f", &sellprice); 

    printf("What are you discounting medium orders?\n"); 
     scanf("%f", &discount_med); 

    printf("What are you discounting large orders?\n"); 
     scanf("%f", &discount_large); 

discount_med_price=discount_med/100 * sellprice; 
med_price= sellprice-discount_med_price; 

discount_large_price=discount_large/100 * sellprice; 
large_price=sellprice-discount_large_price; 


while (sellprice>widget_cost && med_price>widget_cost && large_price>widget_cost){ 

      printf("All prices look good to me!\n"); 
      printf("Good luck!\n"); 
} 


    if (widget_cost>sellprice){ 
     printf("Nick, your base price is too low!"); 
     printf("Good luck!\n"); 
} 
     else if (widget_cost>med_price){ 
      printf("Nick, you are discounting medium purchases too much!\n"); 
      printf("Good luck!\n"); 
} 
      else if (widget_cost>large_price){ 
       printf("Nick, you are discounting large purchases too much!\n"); 
       printf("Goof luck!\n"); 
} 
return 0; 
} 
+0

discount_med聲明int類型的,但你用在scanf函數說明符'%F'。另外,除法將用int來截斷。 – 2015-02-07 22:27:38

+0

你真的需要while循環嗎?如果滿足所有三個條件,那麼您將打印「所有價格對我來說都很好」,因爲一段時間條件永遠不會變成錯誤,並且您將陷入無限循環。我相信你應該把它改成if語句。 – jadhachem 2015-02-07 22:29:34

+0

是的,我剛剛意識到這一點,我已經將它改爲if語句,因爲如果全部符合,它會打印一次。 – Phlash6 2015-02-07 22:32:51

回答

0

您應該將'while'改爲'if'。否則,你的時間將永遠運行,並且在聲明之後你永遠不會得到代碼。雖然意味着「只要條件成立,就重複這一行動」,而你不希望它重複。

你也應該改變你的所有「否則,如果」只是「如果」,因爲從你的描述你想尼克知道賠錢所有價格點。因此,如果med_price和賣出價格都太低,您希望打印兩個警告語句,而不僅僅是第一個。否則,如果情況將永遠不會被看到,如果事先如果或者如果條件得到滿足。

而另一件事情......既然你做一個「的printf(‘祝你好運!\ n’)」在任何情況下,你只需要一次正上方的「返回0」這條線。刪除該語句的所有其他實例。

祝你好運!

+0

我已經改變了語句只的「如果」,然而當我測試樣的條件,基價2,中值折價80,和大優惠90,我仍然得到了第一個條件滿足,當它應該告訴我,大折扣太大。 – Phlash6 2015-02-07 22:53:28

+0

在上述條件下(基本價格,2美元折扣80%,大折扣90%,我的藥物折扣是2折扣的1.6(80%),所以$ .40,這很好,但是平均折扣90% (90%)低於2美元的基數,即0.20美元,這太低了,並且應該觸發第4條if語句,尼克你大量購買大額購買!但是當我在程序中運行這個時,我。我觸發第一個if語句 – Phlash6 2015-02-07 22:57:28

+0

我可能不會使用#define語句爲widget_cost我會把'漂浮widget_cost = 0.40;在主'某處()之類的其他變量聲明後,我不能對此進行測試的權利現在但也許這會有所不同,也許你應該在計算完畢後打印所有的值,這樣就可以確定這些值是你認爲的值。就像'printf(「large_price是%f。\ n」,large_price) ;' – tdub 2015-02-07 23:19:07