2017-02-10 137 views
-6

我得到了我在C++類中旅行的典型距離的功課。但是,在這個問題中,老師說我不能使用「for」循環,而我只允許使用「while循環」,所以我堅持使用這個代碼。如何解決這個C++程序?

問題是小時應顯示單獨行駛的距離,但它顯示每小時行駛的距離總量。

#include <iostream> 
using namespace std; 

int main() 
{ 
    double distance, 
      speed, 
      time, 
      counter=1; 


    cout << "This program will display the total distance travel each hour.\n\n"; 

    cout << " What is the speed of the vehicle in mph? "; 
    cin >> speed; 

    while(speed < 0) 
    { 
     cout << " Please enter a positive number for the speed: "; 
     cin >> speed; 
    } 

    cout << " How many hours has it traveled? "; 
    cin >> time; 

    while(time < 1) 
    { 
     cout << " Please enter a number greater than 1 for the hours: "; 
     cin >> time; 
    } 


    cout << endl; 
    cout << " Hour" << "\t\t" << " Distance Traveled" << endl; 
    cout << " ------------------------------------" << endl; 

    while(counter <= time) 
    { 
     distance = speed * time; 
     cout << counter << "\t\t" << distance << endl; 
     counter++; 

    } 

    return 0; 
} 
+2

while循環和for循環基本上是一樣的。你知道如何用for循環做到這一點嗎? – NathanOliver

+0

是的,我使用for循環,但正如我所說,我的老師正在問我while循環。 –

+0

也許這只是我,但我無法弄清楚這是什麼意思:「*問題是,小時應顯示單獨行駛的距離,但它顯示每小時行駛的距離的總數。*」什麼是單獨列出小時數和列出每小時的旅行數量之間的差異? –

回答

-1

請嘗試,如果它真的是像距離=速度*時間一樣簡單。它看起來像變量countertime混合起來。只需在每個增量處使用counter,即time的本地值。

#include <iostream> 
using namespace std; 

int main() 
{ 
    double distance, 
      speed, 
      time, 
      counter=1; 


    cout << "This program will display the total distance travel each hour.\n\n"; 

    cout << " What is the speed of the vehicle in mph? "; 
    cin >> speed; 

    while(speed < 0) 
    { 
     cout << " Please enter a positive number for the speed: "; 
     cin >> speed; 
    } 

    cout << " How many hours has it traveled? "; 
    cin >> time; 

    while(time < 1) 
    { 
     cout << " Please enter a number greater than 1 for the hours: "; 
     cin >> time; 
    } 


    cout << endl; 
    cout << " Hour" << "\t\t" << " Distance Traveled" << endl; 
    cout << " ------------------------------------" << endl; 

    while(counter <= time) 
    { 
     distance = speed * counter; 
     cout << counter << "\t\t" << distance << endl; 
     counter++; 

    } 

    return 0; 
} 

測試

This program will display the total distance travel each hour. 

What is the speed of the vehicle in mph? 50 
How many hours has it traveled? 5 

Hour  Distance Traveled 
------------------------------------ 
1  50 
2  100 
3  150 
4  200 
5  250 
+0

感謝您的幫助,我很抱歉打擾您。 –

+0

@HugoFederico祝你好運...我希望代碼適合你。 –

1

假設你要計算分別爲每小時行駛的距離(從我可以從代碼中理解);這是因爲每次在counter <= time的while循環中迭代時,都會計算該時間的距離。假設時間= 1小時,您的代碼將計算1小時內行駛的距離並顯示它。當時間爲2小時時,它將分別計算1小時和2小時內行駛的距離(總距離爲2小時)。

例:

time = 2, speed = 60 kmph 

將打印

1 60 
2 120 

其中120是在2小時內的總距離和從第一小時到第二小時不是距離。

如果您需要計算每小時行駛的距離,您的時間應該是恆定的,並且是1小時(假設速度在此期間保持不變)。爲了使用在while循環中,使用:

distance = (speed * counter) - (speed *(counter - 1)) 

距離在第n個小時行進在n個小時減去在第(n-1)小時行進距離總距離。