2014-02-19 89 views
-2

程序很簡單:C:似乎無法找到的bug [do-while循環]

1)它接受用戶的姓名 2)問有多少項目,他已經購買了多少它的成本(Y/N)「 3)如果輸入任何東西> 10項,它會顯示」請輸入一個大於0(零)且小於10(十)的數字。是否要繼續生成另一個帳單?用戶輸入'Y',它應該把他帶到do循環的開始並重新開始。

之間的一切工作正常。這裏是代碼:

int main() 
{ 
    char item[10][10], answer = 'null', name[10]; 
    int price[10], total_item, total_price = 0, i, j = 0, a; 
    float service_tax = 0, vat = 0,total_bill = 0, bill = 0; 

    printf ("Please enter your name: "); 
    scanf ("%s", name); 

    do 
    { 
     printf ("\n Enter the total items purchased (must be more than 0 (zero) and less than 10 (ten): "); 
     scanf (" %d", &total_item); 

     if(total_item > 0 && total_item <= 10) 
    { 
     for(i = 0; i < total_item; i++) 
     { 
      printf ("\nEnter the item name: "); 
      scanf ("%s", item[i]); 

      printf ("\nEnter the item price: "); 
      scanf ("%d", &price[i]); 

      bill = bill + price[i]; 
     } 

     printf("You bill WITHOUT the tax is: %f \n", bill); 

     service_tax = ((bill * 10)/100); 
     vat = ((bill * 12)/100); 

     total_bill = service_tax + vat + bill; 

     printf("The items you've purchased are: \n"); 
     for(i = 0; i < total_item; i++) 
     { 
      printf("\n%s - %d\n", item[i], price[i]); 
     } 

     printf("Your total bill is: %3f", total_bill); 

     printf ("Your bill# is %s-%d-%d", &name, total_item, rand()%1000); 
    } 

    else 
    { 
     printf("\n %s, please enter a number greater than 0 (zero) and less than 10 (ten)", &name); 

     printf("\nDo you want to continue generating another bill? (Y/N)\n"); 
     scanf (" %c", &answer); 
    } 

}while ((answer == 'y') || (answer = 'Y')); 

return 0;} 

請幫助我!對於我的生活,我似乎無法弄清楚爲什麼do-while循環無法正常工作。

非常感謝您的幫助!

+2

answer ='Y'更改爲回答=='Y' – sashkello

+0

'answer ='Y''在'while'子句中可疑,您的意思是'answer =='Y' '? – Teetoo

回答

6

此:

while ((answer == 'y') || (answer = 'Y')); 

使用=時,這意味着==。以上條件將始終爲真,因爲'Y'不爲零。

有人阻止自己不受總是在右手側寫變量有這個問題,即上述本來(正確)寫成

while (('y' == answer) || ('Y' == answer)); 

如果這樣寫,如果你錯過了一個=由於左側的文字不可分配,因此您會收到錯誤消息。

我不喜歡這個,我覺得很難閱讀。當比較兩個變量時,它也會崩潰,這並不罕見。

+0

...正確使用編譯器警告會告訴你的東西。 – DevSolar

+1

...雖然我關掉了警告,並且相信我並不孤單。在'if'中的賦值是完全可以接受的,並且在數學代碼中經常使用。 – Bathsheba

0

Typo。你有answer = 'Y',但你的意思是answer == 'Y'

一些民間寫作'Y' == answer作爲一個習慣的過程,因爲錯誤的'Y' = answer將導致編譯時間失敗。

-1

while while to while((answer =='y')||(answer =='Y'));

它的工作。而我不是一個老兄..

+0

是的,你是匿名人 –