我得到了我在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;
}
while循環和for循環基本上是一樣的。你知道如何用for循環做到這一點嗎? – NathanOliver
是的,我使用for循環,但正如我所說,我的老師正在問我while循環。 –
也許這只是我,但我無法弄清楚這是什麼意思:「*問題是,小時應顯示單獨行駛的距離,但它顯示每小時行駛的距離的總數。*」什麼是單獨列出小時數和列出每小時的旅行數量之間的差異? –