2011-02-09 227 views
1
/*Taking input from user to calculate the cost of a travel plan                                            
using the number of travelers/ number of stops/ cost of each stop                                           
giving both the half cost of a trip and its full price*/ 

int calculate(int total); 

#include <stdio.h> 
int main(void) 
{ 
    float customer, stops, response, cost, i, stop, total, halfcost, totaltrip; 
    i=0; 
    printf("Welcome to Airline express.\n"); 

    printf("Would you like to calculate the cost of a trip?"); 

    scanf("%f", &response); 
    while (response != 0) 
    { 
     printf("Please enter how many customer will be traveling. Children under 12 are counted as .5:"); 
     scanf("%f", &customer); 
     if (customer < 0) 
      customer = 3; 

     printf("Please enter how many stops there are:"); 
     scanf("%f", &stop); 

     while (i<stop) 
     { 
      printf("Please enter cost of the next stop:"); 
      scanf("%f", &cost); 
      if (cost < 0) 
       cost = 100; 
      total +=cost; 
      i++; 
     } 

     halfcost = calculate(total); 
     printf("Half cost is: %f", halfcost); 


     totaltrip = total * customer; 
     printf("Total cost for trip is: %f\n", totaltrip); 

     printf("Would you like to calculate another trip?"); 
     scanf("%f", &response); 
    } 
    return 0; 
} 

int calculate(int total) 
{ 
    return total/2; 
} 

我遇到了輸入問題,我試圖讓循環運行,因爲用戶請求另一個計算。但是,當它再次運行另一個測試時,它會保持先前測試的輸入是否有辦法將變量重置爲0? 我曾嘗試分配循環內部和外部的所有變量,但我有點不知道該從哪裏去。while循環問題

+3

你真的應該學習整數。對於可數的事物,「float」不是一個合適的數據類型(如停止數)。 'total'是可能應該接受小數值的少數幾個變量之一,並且可以通過'int'參數傳遞它。 –

+1

你永遠不會初始化'total'(甚至是第一次);在開始向其添加「成本」之前,不能保證爲0。 –

+1

「響應」也應該是一個字符......只是一個Y/Y或N/N是一個直觀的輸入。 –

回答

2

將變量的聲明移到循環中。

while (response != 0) 
{ 
    float customer = 0, stops = 0, response = 0, cost = 0, i = 0, stop = 0, total = 0, halfcost = 0, totaltrip = 0; 
    ... 
} 
+1

它的工作:D,但有一個輕微的問題我可以將它們聲明在函數的頂部,而不是在循環內,或者它必須在循環內部才能正常工作 –

+2

注意到C中對變量聲明的需求是它在一個塊的開始;很多時候這(誤)被解釋爲要求它是該函數的開始。把你的變量聲明放在儘可能接近你需要的地方是一個有用的模式。 – Keith

+1

在聲明之前使用'response'不會起作用。 –