我得到了我的c ++课程中典型距离的作业。然而,在这个问题上,老师说我不能使用" for"循环,我只允许使用" while循环",所以我坚持使用此代码。
问题是小时应该显示单独行驶的距离,但它显示每小时行驶距离的总量。
#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;
}
答案 0 :(得分:1)
假设你想分别计算每个小时的行走距离(从我能从代码中理解);这是因为每次在counter <= time
的while循环中迭代时,都会计算该时间量的距离。假设时间= 1小时,您的代码计算1小时内行进的距离并显示它。当时间为2小时时,它分别计算1小时和2小时(总距离不是2小时)的行进距离。
例如:
time = 2, speed = 60 kmph
将打印
1 60
2 120
其中120是2小时内的总距离,而不是从1小时到第2小时的距离。
如果您需要计算每小时行驶的距离,您的时间应该是恒定的,并且是1小时(假设速度在整个时间内保持不变)。要在while循环中使用它,请使用:
distance = (speed * counter) - (speed *(counter - 1))
在第n小时行进的距离是n小时内的总距离减去(n-1)小时内的行进距离。
答案 1 :(得分:-1)
如果它真的像距离=速度*时间一样简单,请尝试。您似乎将变量print(df)
X Y
0 1.0 8
1 2.0 3
2 8.0 2
3 6.0 7
4 1.0 2
5 3.0 2
和counter
混为一谈。只需在每个增量使用time
,即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;
}