編寫一個程序,詢問三位跑步者的名字以及每位參加比賽的每個 所花費的時間。該計劃應顯示第一名,第二名和第三名。 輸入驗證:只接受時間的正數。如果程序更簡單,代碼冗餘更少(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