编写一个程序,询问三位跑步者的名字以及每位参加比赛的每个 所花费的时间。该计划应显示第一名,第二名和第三名。 输入验证:只接受时间的正数。如果程序更简单,代码冗余更少(C++),你会怎么做呢?
我的代码
#include <iostream>
#include <string>
using namespace std;
int main()
{
string runner1, runner2, runner3;
int time1, time2, time3;
cout << "Please enter the names of three runners" << endl;
cin >> runner1 >> runner2 >> runner3;
cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
cin >> time1;
cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
cin >> time2;
cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
cin >> time3;
if (time1 < time2 && time1 < time3)
{
cout << runner1 << " is 1st place!" << endl;
if (time2 < time3)
{
cout << runner2 << " is 2nd place!" << endl;
cout << runner3 << " is 3rd place!" << endl;
}
else if (time3 < time2)
{
cout << runner3 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else if (time2 < time1 && time2 < time3)
{
cout << runner2 << " is 1st place!" << endl;
if (time1 < time3)
{
cout << runner1 << " is 2nd place!" << endl;
cout << runner3 << " is 3rd place!" << endl;
}
else if (time3 < time1)
{
cout << runner3 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else if (time3 < time2 && time3 < time1)
{
cout << runner3 << " is 1st Place!" << endl;
if (time2 < time1)
{
cout << runner2 << " is 2nd place!" << endl;
cout << runner1 << " is 3rd place!" << endl;
}
else if (time1 < time2)
{
cout << runner1 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else
{
cout << "Error! Please restart the program and input a positive value" << endl;
}
return 0;
}
您展示该方案,不是* *工作?它是否构建?它运行吗?它会产生预期的结果吗?那么你想要的是*代码审查*,你应该在http://codereview.stackexchange.com/而不是在这里发布。 –
@OP我会从改进代码布局开始,所以它会更好。 –
由于问题是以它的方式编写的,所以它听起来像是我的作业。所以这里只是一些提示:1。每个跑步者都有相应的时间,所以将它们绑定到一个类或结构中是有意义的。来自“简明英汉词典”这个班级的成员可以通过比较他们的运行时间进行排序3.通过将它们存储在STL容器中对它们进行排序,并通过'std :: sort'(或类似的东西)对它们进行排序。4.通过迭代排序后的容器来打印出谁有。试试看,如果你有问题,请回到这里。 SO不是没有代码写入服务。 – muXXmit2X