/*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循環問題
你真的應該學習整數。對於可數的事物,「float」不是一個合適的數據類型(如停止數)。 'total'是可能應該接受小數值的少數幾個變量之一,並且可以通過'int'參數傳遞它。 –
你永遠不會初始化'total'(甚至是第一次);在開始向其添加「成本」之前,不能保證爲0。 –
「響應」也應該是一個字符......只是一個Y/Y或N/N是一個直觀的輸入。 –